circuituse.c 57 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588
  1. /* Copyright (c) 2001 Matej Pfajfar.
  2. * Copyright (c) 2001-2004, Roger Dingledine.
  3. * Copyright (c) 2004-2006, Roger Dingledine, Nick Mathewson.
  4. * Copyright (c) 2007-2011, The Tor Project, Inc. */
  5. /* See LICENSE for licensing information */
  6. /**
  7. * \file circuituse.c
  8. * \brief Launch the right sort of circuits and attach streams to them.
  9. **/
  10. #include "or.h"
  11. /********* START VARIABLES **********/
  12. extern circuit_t *global_circuitlist; /* from circuitlist.c */
  13. /********* END VARIABLES ************/
  14. static void circuit_expire_old_circuits_clientside(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_clientside(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_clientside(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. /** How long do we wait before killing circuits with the properties
  599. * described below?
  600. *
  601. * Probably we could choose a number here as low as 5 to 10 seconds,
  602. * since these circs are used for begindir, and a) generally you either
  603. * ask another begindir question right after or you don't for a long time,
  604. * b) clients at least through 0.2.1.x choose from the whole set of
  605. * directory mirrors at each choice, and c) re-establishing a one-hop
  606. * circuit via create-fast is a light operation assuming the TLS conn is
  607. * still there.
  608. *
  609. * I expect "b" to go away one day when we move to using directory
  610. * guards, but I think "a" and "c" are good enough reasons that a low
  611. * number is safe even then.
  612. */
  613. #define IDLE_ONE_HOP_CIRC_TIMEOUT 60
  614. /** Find each non-origin circuit that has been unused for too long,
  615. * has no streams on it, used a create_fast, and ends here: mark it
  616. * for close.
  617. */
  618. void
  619. circuit_expire_old_circuits_serverside(time_t now)
  620. {
  621. circuit_t *circ;
  622. or_circuit_t *or_circ;
  623. time_t cutoff = now - IDLE_ONE_HOP_CIRC_TIMEOUT;
  624. for (circ = global_circuitlist; circ; circ = circ->next) {
  625. if (circ->marked_for_close || CIRCUIT_IS_ORIGIN(circ))
  626. continue;
  627. or_circ = TO_OR_CIRCUIT(circ);
  628. /* If the circuit has been idle for too long, and there are no streams
  629. * on it, and it ends here, and it used a create_fast, mark it for close.
  630. */
  631. if (or_circ->is_first_hop && !circ->n_conn &&
  632. !or_circ->n_streams && !or_circ->resolving_streams &&
  633. or_circ->p_conn &&
  634. or_circ->p_conn->timestamp_last_added_nonpadding <= cutoff) {
  635. log_info(LD_CIRC, "Closing circ_id %d (empty %d secs ago)",
  636. or_circ->p_circ_id,
  637. (int)(now - or_circ->p_conn->timestamp_last_added_nonpadding));
  638. circuit_mark_for_close(circ, END_CIRC_REASON_FINISHED);
  639. }
  640. }
  641. }
  642. /** Number of testing circuits we want open before testing our bandwidth. */
  643. #define NUM_PARALLEL_TESTING_CIRCS 4
  644. /** True iff we've ever had enough testing circuits open to test our
  645. * bandwidth. */
  646. static int have_performed_bandwidth_test = 0;
  647. /** Reset have_performed_bandwidth_test, so we'll start building
  648. * testing circuits again so we can exercise our bandwidth. */
  649. void
  650. reset_bandwidth_test(void)
  651. {
  652. have_performed_bandwidth_test = 0;
  653. }
  654. /** Return 1 if we've already exercised our bandwidth, or if we
  655. * have fewer than NUM_PARALLEL_TESTING_CIRCS testing circuits
  656. * established or on the way. Else return 0.
  657. */
  658. int
  659. circuit_enough_testing_circs(void)
  660. {
  661. circuit_t *circ;
  662. int num = 0;
  663. if (have_performed_bandwidth_test)
  664. return 1;
  665. for (circ = global_circuitlist; circ; circ = circ->next) {
  666. if (!circ->marked_for_close && CIRCUIT_IS_ORIGIN(circ) &&
  667. circ->purpose == CIRCUIT_PURPOSE_TESTING &&
  668. circ->state == CIRCUIT_STATE_OPEN)
  669. num++;
  670. }
  671. return num >= NUM_PARALLEL_TESTING_CIRCS;
  672. }
  673. /** A testing circuit has completed. Take whatever stats we want.
  674. * Noticing reachability is taken care of in onionskin_answer(),
  675. * so there's no need to record anything here. But if we still want
  676. * to do the bandwidth test, and we now have enough testing circuits
  677. * open, do it.
  678. */
  679. static void
  680. circuit_testing_opened(origin_circuit_t *circ)
  681. {
  682. if (have_performed_bandwidth_test ||
  683. !check_whether_orport_reachable()) {
  684. /* either we've already done everything we want with testing circuits,
  685. * or this testing circuit became open due to a fluke, e.g. we picked
  686. * a last hop where we already had the connection open due to an
  687. * outgoing local circuit. */
  688. circuit_mark_for_close(TO_CIRCUIT(circ), END_CIRC_AT_ORIGIN);
  689. } else if (circuit_enough_testing_circs()) {
  690. router_perform_bandwidth_test(NUM_PARALLEL_TESTING_CIRCS, time(NULL));
  691. have_performed_bandwidth_test = 1;
  692. } else
  693. consider_testing_reachability(1, 0);
  694. }
  695. /** A testing circuit has failed to build. Take whatever stats we want. */
  696. static void
  697. circuit_testing_failed(origin_circuit_t *circ, int at_last_hop)
  698. {
  699. if (server_mode(get_options()) && check_whether_orport_reachable())
  700. return;
  701. log_info(LD_GENERAL,
  702. "Our testing circuit (to see if your ORPort is reachable) "
  703. "has failed. I'll try again later.");
  704. /* These aren't used yet. */
  705. (void)circ;
  706. (void)at_last_hop;
  707. }
  708. /** The circuit <b>circ</b> has just become open. Take the next
  709. * step: for rendezvous circuits, we pass circ to the appropriate
  710. * function in rendclient or rendservice. For general circuits, we
  711. * call connection_ap_attach_pending, which looks for pending streams
  712. * that could use circ.
  713. */
  714. void
  715. circuit_has_opened(origin_circuit_t *circ)
  716. {
  717. control_event_circuit_status(circ, CIRC_EVENT_BUILT, 0);
  718. switch (TO_CIRCUIT(circ)->purpose) {
  719. case CIRCUIT_PURPOSE_C_ESTABLISH_REND:
  720. rend_client_rendcirc_has_opened(circ);
  721. connection_ap_attach_pending();
  722. break;
  723. case CIRCUIT_PURPOSE_C_INTRODUCING:
  724. rend_client_introcirc_has_opened(circ);
  725. break;
  726. case CIRCUIT_PURPOSE_C_GENERAL:
  727. /* Tell any AP connections that have been waiting for a new
  728. * circuit that one is ready. */
  729. connection_ap_attach_pending();
  730. break;
  731. case CIRCUIT_PURPOSE_S_ESTABLISH_INTRO:
  732. /* at Bob, waiting for introductions */
  733. rend_service_intro_has_opened(circ);
  734. break;
  735. case CIRCUIT_PURPOSE_S_CONNECT_REND:
  736. /* at Bob, connecting to rend point */
  737. rend_service_rendezvous_has_opened(circ);
  738. break;
  739. case CIRCUIT_PURPOSE_TESTING:
  740. circuit_testing_opened(circ);
  741. break;
  742. /* default:
  743. * This won't happen in normal operation, but might happen if the
  744. * controller did it. Just let it slide. */
  745. }
  746. }
  747. /** Called whenever a circuit could not be successfully built.
  748. */
  749. void
  750. circuit_build_failed(origin_circuit_t *circ)
  751. {
  752. /* we should examine circ and see if it failed because of
  753. * the last hop or an earlier hop. then use this info below.
  754. */
  755. int failed_at_last_hop = 0;
  756. /* If the last hop isn't open, and the second-to-last is, we failed
  757. * at the last hop. */
  758. if (circ->cpath &&
  759. circ->cpath->prev->state != CPATH_STATE_OPEN &&
  760. circ->cpath->prev->prev->state == CPATH_STATE_OPEN) {
  761. failed_at_last_hop = 1;
  762. }
  763. if (circ->cpath &&
  764. circ->cpath->state != CPATH_STATE_OPEN) {
  765. /* We failed at the first hop. If there's an OR connection
  766. * to blame, blame it. Also, avoid this relay for a while, and
  767. * fail any one-hop directory fetches destined for it. */
  768. const char *n_conn_id = circ->cpath->extend_info->identity_digest;
  769. if (circ->_base.n_conn) {
  770. or_connection_t *n_conn = circ->_base.n_conn;
  771. log_info(LD_OR,
  772. "Our circuit failed to get a response from the first hop "
  773. "(%s:%d). I'm going to try to rotate to a better connection.",
  774. n_conn->_base.address, n_conn->_base.port);
  775. n_conn->is_bad_for_new_circs = 1;
  776. }
  777. if (n_conn_id) {
  778. entry_guard_register_connect_status(n_conn_id, 0, 1, time(NULL));
  779. /* if there are any one-hop streams waiting on this circuit, fail
  780. * them now so they can retry elsewhere. */
  781. connection_ap_fail_onehop(n_conn_id, circ->build_state);
  782. }
  783. }
  784. switch (circ->_base.purpose) {
  785. case CIRCUIT_PURPOSE_C_GENERAL:
  786. /* If we never built the circuit, note it as a failure. */
  787. circuit_increment_failure_count();
  788. if (failed_at_last_hop) {
  789. /* Make sure any streams that demand our last hop as their exit
  790. * know that it's unlikely to happen. */
  791. circuit_discard_optional_exit_enclaves(circ->cpath->prev->extend_info);
  792. }
  793. break;
  794. case CIRCUIT_PURPOSE_TESTING:
  795. circuit_testing_failed(circ, failed_at_last_hop);
  796. break;
  797. case CIRCUIT_PURPOSE_S_ESTABLISH_INTRO:
  798. /* at Bob, waiting for introductions */
  799. if (circ->_base.state != CIRCUIT_STATE_OPEN) {
  800. circuit_increment_failure_count();
  801. }
  802. /* no need to care here, because bob will rebuild intro
  803. * points periodically. */
  804. break;
  805. case CIRCUIT_PURPOSE_C_INTRODUCING:
  806. /* at Alice, connecting to intro point */
  807. /* Don't increment failure count, since Bob may have picked
  808. * the introduction point maliciously */
  809. /* Alice will pick a new intro point when this one dies, if
  810. * the stream in question still cares. No need to act here. */
  811. break;
  812. case CIRCUIT_PURPOSE_C_ESTABLISH_REND:
  813. /* at Alice, waiting for Bob */
  814. circuit_increment_failure_count();
  815. /* Alice will pick a new rend point when this one dies, if
  816. * the stream in question still cares. No need to act here. */
  817. break;
  818. case CIRCUIT_PURPOSE_S_CONNECT_REND:
  819. /* at Bob, connecting to rend point */
  820. /* Don't increment failure count, since Alice may have picked
  821. * the rendezvous point maliciously */
  822. log_info(LD_REND,
  823. "Couldn't connect to Alice's chosen rend point %s "
  824. "(%s hop failed).",
  825. escaped(build_state_get_exit_nickname(circ->build_state)),
  826. failed_at_last_hop?"last":"non-last");
  827. rend_service_relaunch_rendezvous(circ);
  828. break;
  829. /* default:
  830. * This won't happen in normal operation, but might happen if the
  831. * controller did it. Just let it slide. */
  832. }
  833. }
  834. /** Number of consecutive failures so far; should only be touched by
  835. * circuit_launch_new and circuit_*_failure_count.
  836. */
  837. static int n_circuit_failures = 0;
  838. /** Before the last time we called circuit_reset_failure_count(), were
  839. * there a lot of failures? */
  840. static int did_circs_fail_last_period = 0;
  841. /** Don't retry launching a new circuit if we try this many times with no
  842. * success. */
  843. #define MAX_CIRCUIT_FAILURES 5
  844. /** Launch a new circuit; see circuit_launch_by_extend_info() for
  845. * details on arguments. */
  846. origin_circuit_t *
  847. circuit_launch_by_router(uint8_t purpose,
  848. routerinfo_t *exit, int flags)
  849. {
  850. origin_circuit_t *circ;
  851. extend_info_t *info = NULL;
  852. if (exit)
  853. info = extend_info_from_router(exit);
  854. circ = circuit_launch_by_extend_info(purpose, info, flags);
  855. if (info)
  856. extend_info_free(info);
  857. return circ;
  858. }
  859. /** Launch a new circuit with purpose <b>purpose</b> and exit node
  860. * <b>extend_info</b> (or NULL to select a random exit node). If flags
  861. * contains CIRCLAUNCH_NEED_UPTIME, choose among routers with high uptime. If
  862. * CIRCLAUNCH_NEED_CAPACITY is set, choose among routers with high bandwidth.
  863. * If CIRCLAUNCH_IS_INTERNAL is true, the last hop need not be an exit node.
  864. * If CIRCLAUNCH_ONEHOP_TUNNEL is set, the circuit will have only one hop.
  865. * Return the newly allocated circuit on success, or NULL on failure. */
  866. origin_circuit_t *
  867. circuit_launch_by_extend_info(uint8_t purpose,
  868. extend_info_t *extend_info,
  869. int flags)
  870. {
  871. origin_circuit_t *circ;
  872. int onehop_tunnel = (flags & CIRCLAUNCH_ONEHOP_TUNNEL) != 0;
  873. if (!onehop_tunnel && !router_have_minimum_dir_info()) {
  874. log_debug(LD_CIRC,"Haven't fetched enough directory info yet; canceling "
  875. "circuit launch.");
  876. return NULL;
  877. }
  878. if ((extend_info || purpose != CIRCUIT_PURPOSE_C_GENERAL) &&
  879. purpose != CIRCUIT_PURPOSE_TESTING && !onehop_tunnel) {
  880. /* see if there are appropriate circs available to cannibalize. */
  881. /* XXX if we're planning to add a hop, perhaps we want to look for
  882. * internal circs rather than exit circs? -RD */
  883. circ = circuit_find_to_cannibalize(purpose, extend_info, flags);
  884. if (circ) {
  885. log_info(LD_CIRC,"Cannibalizing circ '%s' for purpose %d",
  886. build_state_get_exit_nickname(circ->build_state), purpose);
  887. circ->_base.purpose = purpose;
  888. /* reset the birth date of this circ, else expire_building
  889. * will see it and think it's been trying to build since it
  890. * began. */
  891. circ->_base.timestamp_created = time(NULL);
  892. switch (purpose) {
  893. case CIRCUIT_PURPOSE_C_ESTABLISH_REND:
  894. case CIRCUIT_PURPOSE_S_ESTABLISH_INTRO:
  895. /* it's ready right now */
  896. break;
  897. case CIRCUIT_PURPOSE_C_INTRODUCING:
  898. case CIRCUIT_PURPOSE_S_CONNECT_REND:
  899. case CIRCUIT_PURPOSE_C_GENERAL:
  900. /* need to add a new hop */
  901. tor_assert(extend_info);
  902. if (circuit_extend_to_new_exit(circ, extend_info) < 0)
  903. return NULL;
  904. break;
  905. default:
  906. log_warn(LD_BUG,
  907. "unexpected purpose %d when cannibalizing a circ.",
  908. purpose);
  909. tor_fragile_assert();
  910. return NULL;
  911. }
  912. return circ;
  913. }
  914. }
  915. if (did_circs_fail_last_period &&
  916. n_circuit_failures > MAX_CIRCUIT_FAILURES) {
  917. /* too many failed circs in a row. don't try. */
  918. // log_fn(LOG_INFO,"%d failures so far, not trying.",n_circuit_failures);
  919. return NULL;
  920. }
  921. /* try a circ. if it fails, circuit_mark_for_close will increment
  922. * n_circuit_failures */
  923. return circuit_establish_circuit(purpose, extend_info, flags);
  924. }
  925. /** Record another failure at opening a general circuit. When we have
  926. * too many, we'll stop trying for the remainder of this minute.
  927. */
  928. static void
  929. circuit_increment_failure_count(void)
  930. {
  931. ++n_circuit_failures;
  932. log_debug(LD_CIRC,"n_circuit_failures now %d.",n_circuit_failures);
  933. }
  934. /** Reset the failure count for opening general circuits. This means
  935. * we will try MAX_CIRCUIT_FAILURES times more (if necessary) before
  936. * stopping again.
  937. */
  938. void
  939. circuit_reset_failure_count(int timeout)
  940. {
  941. if (timeout && n_circuit_failures > MAX_CIRCUIT_FAILURES)
  942. did_circs_fail_last_period = 1;
  943. else
  944. did_circs_fail_last_period = 0;
  945. n_circuit_failures = 0;
  946. }
  947. /** Find an open circ that we're happy to use for <b>conn</b> and return 1. If
  948. * there isn't one, and there isn't one on the way, launch one and return
  949. * 0. If it will never work, return -1.
  950. *
  951. * Write the found or in-progress or launched circ into *circp.
  952. */
  953. static int
  954. circuit_get_open_circ_or_launch(edge_connection_t *conn,
  955. uint8_t desired_circuit_purpose,
  956. origin_circuit_t **circp)
  957. {
  958. origin_circuit_t *circ;
  959. int check_exit_policy;
  960. int need_uptime, need_internal;
  961. int want_onehop;
  962. or_options_t *options = get_options();
  963. tor_assert(conn);
  964. tor_assert(circp);
  965. tor_assert(conn->_base.state == AP_CONN_STATE_CIRCUIT_WAIT);
  966. check_exit_policy =
  967. conn->socks_request->command == SOCKS_COMMAND_CONNECT &&
  968. !conn->use_begindir &&
  969. !connection_edge_is_rendezvous_stream(conn);
  970. want_onehop = conn->want_onehop;
  971. need_uptime = !conn->want_onehop && !conn->use_begindir &&
  972. smartlist_string_num_isin(options->LongLivedPorts,
  973. conn->socks_request->port);
  974. need_internal = desired_circuit_purpose != CIRCUIT_PURPOSE_C_GENERAL;
  975. circ = circuit_get_best(conn, 1, desired_circuit_purpose,
  976. need_uptime, need_internal);
  977. if (circ) {
  978. *circp = circ;
  979. return 1; /* we're happy */
  980. }
  981. if (!want_onehop && !router_have_minimum_dir_info()) {
  982. if (!connection_get_by_type(CONN_TYPE_DIR)) {
  983. int severity = LOG_NOTICE;
  984. /* FFFF if this is a tunneled directory fetch, don't yell
  985. * as loudly. the user doesn't even know it's happening. */
  986. if (options->UseBridges && bridges_known_but_down()) {
  987. log_fn(severity, LD_APP|LD_DIR,
  988. "Application request when we're believed to be "
  989. "offline. Optimistically trying known bridges again.");
  990. bridges_retry_all();
  991. } else if (!options->UseBridges || any_bridge_descriptors_known()) {
  992. log_fn(severity, LD_APP|LD_DIR,
  993. "Application request when we're believed to be "
  994. "offline. Optimistically trying directory fetches again.");
  995. routerlist_retry_directory_downloads(time(NULL));
  996. }
  997. }
  998. /* the stream will be dealt with when router_have_minimum_dir_info becomes
  999. * 1, or when all directory attempts fail and directory_all_unreachable()
  1000. * kills it.
  1001. */
  1002. return 0;
  1003. }
  1004. /* Do we need to check exit policy? */
  1005. if (check_exit_policy) {
  1006. if (!conn->chosen_exit_name) {
  1007. struct in_addr in;
  1008. uint32_t addr = 0;
  1009. if (tor_inet_aton(conn->socks_request->address, &in))
  1010. addr = ntohl(in.s_addr);
  1011. if (router_exit_policy_all_routers_reject(addr,
  1012. conn->socks_request->port,
  1013. need_uptime)) {
  1014. log_notice(LD_APP,
  1015. "No Tor server allows exit to %s:%d. Rejecting.",
  1016. safe_str(conn->socks_request->address),
  1017. conn->socks_request->port);
  1018. return -1;
  1019. }
  1020. } else {
  1021. /* XXXX022 Duplicates checks in connection_ap_handshake_attach_circuit */
  1022. routerinfo_t *router = router_get_by_nickname(conn->chosen_exit_name, 1);
  1023. int opt = conn->chosen_exit_optional;
  1024. if (router && !connection_ap_can_use_exit(conn, router)) {
  1025. log_fn(opt ? LOG_INFO : LOG_WARN, LD_APP,
  1026. "Requested exit point '%s' would refuse request. %s.",
  1027. conn->chosen_exit_name, opt ? "Trying others" : "Closing");
  1028. if (opt) {
  1029. conn->chosen_exit_optional = 0;
  1030. tor_free(conn->chosen_exit_name);
  1031. /* Try again. */
  1032. return circuit_get_open_circ_or_launch(conn,
  1033. desired_circuit_purpose,
  1034. circp);
  1035. }
  1036. return -1;
  1037. }
  1038. }
  1039. }
  1040. /* is one already on the way? */
  1041. circ = circuit_get_best(conn, 0, desired_circuit_purpose,
  1042. need_uptime, need_internal);
  1043. if (circ)
  1044. log_debug(LD_CIRC, "one on the way!");
  1045. if (!circ) {
  1046. extend_info_t *extend_info=NULL;
  1047. uint8_t new_circ_purpose;
  1048. if (desired_circuit_purpose == CIRCUIT_PURPOSE_C_INTRODUCE_ACK_WAIT) {
  1049. /* need to pick an intro point */
  1050. tor_assert(conn->rend_data);
  1051. extend_info = rend_client_get_random_intro(conn->rend_data);
  1052. if (!extend_info) {
  1053. log_info(LD_REND,
  1054. "No intro points for '%s': re-fetching service descriptor.",
  1055. safe_str(conn->rend_data->onion_address));
  1056. /* Fetch both, v0 and v2 rend descriptors in parallel. Use whichever
  1057. * arrives first. Exception: When using client authorization, only
  1058. * fetch v2 descriptors.*/
  1059. rend_client_refetch_v2_renddesc(conn->rend_data);
  1060. if (conn->rend_data->auth_type == REND_NO_AUTH)
  1061. rend_client_refetch_renddesc(conn->rend_data->onion_address);
  1062. conn->_base.state = AP_CONN_STATE_RENDDESC_WAIT;
  1063. return 0;
  1064. }
  1065. log_info(LD_REND,"Chose '%s' as intro point for '%s'.",
  1066. extend_info->nickname,
  1067. safe_str(conn->rend_data->onion_address));
  1068. }
  1069. /* If we have specified a particular exit node for our
  1070. * connection, then be sure to open a circuit to that exit node.
  1071. */
  1072. if (desired_circuit_purpose == CIRCUIT_PURPOSE_C_GENERAL) {
  1073. if (conn->chosen_exit_name) {
  1074. routerinfo_t *r;
  1075. int opt = conn->chosen_exit_optional;
  1076. r = router_get_by_nickname(conn->chosen_exit_name, 1);
  1077. if (r) {
  1078. extend_info = extend_info_from_router(r);
  1079. } else {
  1080. log_debug(LD_DIR, "considering %d, %s",
  1081. want_onehop, conn->chosen_exit_name);
  1082. if (want_onehop && conn->chosen_exit_name[0] == '$') {
  1083. /* We're asking for a one-hop circuit to a router that
  1084. * we don't have a routerinfo about. Make up an extend_info. */
  1085. char digest[DIGEST_LEN];
  1086. char *hexdigest = conn->chosen_exit_name+1;
  1087. tor_addr_t addr;
  1088. if (strlen(hexdigest) < HEX_DIGEST_LEN ||
  1089. base16_decode(digest,DIGEST_LEN,hexdigest,HEX_DIGEST_LEN)<0) {
  1090. log_info(LD_DIR, "Broken exit digest on tunnel conn. Closing.");
  1091. return -1;
  1092. }
  1093. if (tor_addr_from_str(&addr, conn->socks_request->address) < 0) {
  1094. log_info(LD_DIR, "Broken address %s on tunnel conn. Closing.",
  1095. escaped_safe_str(conn->socks_request->address));
  1096. return -1;
  1097. }
  1098. extend_info = extend_info_alloc(conn->chosen_exit_name+1,
  1099. digest, NULL, &addr,
  1100. conn->socks_request->port);
  1101. } else {
  1102. /* We will need an onion key for the router, and we
  1103. * don't have one. Refuse or relax requirements. */
  1104. log_fn(opt ? LOG_INFO : LOG_WARN, LD_APP,
  1105. "Requested exit point '%s' is not known. %s.",
  1106. conn->chosen_exit_name, opt ? "Trying others" : "Closing");
  1107. if (opt) {
  1108. conn->chosen_exit_optional = 0;
  1109. tor_free(conn->chosen_exit_name);
  1110. /* Try again with no requested exit */
  1111. return circuit_get_open_circ_or_launch(conn,
  1112. desired_circuit_purpose,
  1113. circp);
  1114. }
  1115. return -1;
  1116. }
  1117. }
  1118. }
  1119. }
  1120. if (desired_circuit_purpose == CIRCUIT_PURPOSE_C_REND_JOINED)
  1121. new_circ_purpose = CIRCUIT_PURPOSE_C_ESTABLISH_REND;
  1122. else if (desired_circuit_purpose == CIRCUIT_PURPOSE_C_INTRODUCE_ACK_WAIT)
  1123. new_circ_purpose = CIRCUIT_PURPOSE_C_INTRODUCING;
  1124. else
  1125. new_circ_purpose = desired_circuit_purpose;
  1126. {
  1127. int flags = CIRCLAUNCH_NEED_CAPACITY;
  1128. if (want_onehop) flags |= CIRCLAUNCH_ONEHOP_TUNNEL;
  1129. if (need_uptime) flags |= CIRCLAUNCH_NEED_UPTIME;
  1130. if (need_internal) flags |= CIRCLAUNCH_IS_INTERNAL;
  1131. circ = circuit_launch_by_extend_info(new_circ_purpose, extend_info,
  1132. flags);
  1133. }
  1134. if (extend_info)
  1135. extend_info_free(extend_info);
  1136. if (desired_circuit_purpose != CIRCUIT_PURPOSE_C_GENERAL) {
  1137. /* help predict this next time */
  1138. rep_hist_note_used_internal(time(NULL), need_uptime, 1);
  1139. if (circ) {
  1140. /* write the service_id into circ */
  1141. circ->rend_data = rend_data_dup(conn->rend_data);
  1142. if (circ->_base.purpose == CIRCUIT_PURPOSE_C_ESTABLISH_REND &&
  1143. circ->_base.state == CIRCUIT_STATE_OPEN)
  1144. rend_client_rendcirc_has_opened(circ);
  1145. }
  1146. }
  1147. }
  1148. if (!circ)
  1149. log_info(LD_APP,
  1150. "No safe circuit (purpose %d) ready for edge "
  1151. "connection; delaying.",
  1152. desired_circuit_purpose);
  1153. *circp = circ;
  1154. return 0;
  1155. }
  1156. /** Return true iff <b>crypt_path</b> is one of the crypt_paths for
  1157. * <b>circ</b>. */
  1158. static int
  1159. cpath_is_on_circuit(origin_circuit_t *circ, crypt_path_t *crypt_path)
  1160. {
  1161. crypt_path_t *cpath, *cpath_next = NULL;
  1162. for (cpath = circ->cpath; cpath_next != circ->cpath; cpath = cpath_next) {
  1163. cpath_next = cpath->next;
  1164. if (crypt_path == cpath)
  1165. return 1;
  1166. }
  1167. return 0;
  1168. }
  1169. /** Attach the AP stream <b>apconn</b> to circ's linked list of
  1170. * p_streams. Also set apconn's cpath_layer to <b>cpath</b>, or to the last
  1171. * hop in circ's cpath if <b>cpath</b> is NULL.
  1172. */
  1173. static void
  1174. link_apconn_to_circ(edge_connection_t *apconn, origin_circuit_t *circ,
  1175. crypt_path_t *cpath)
  1176. {
  1177. /* add it into the linked list of streams on this circuit */
  1178. log_debug(LD_APP|LD_CIRC, "attaching new conn to circ. n_circ_id %d.",
  1179. circ->_base.n_circ_id);
  1180. /* reset it, so we can measure circ timeouts */
  1181. apconn->_base.timestamp_lastread = time(NULL);
  1182. apconn->next_stream = circ->p_streams;
  1183. apconn->on_circuit = TO_CIRCUIT(circ);
  1184. /* assert_connection_ok(conn, time(NULL)); */
  1185. circ->p_streams = apconn;
  1186. if (cpath) { /* we were given one; use it */
  1187. tor_assert(cpath_is_on_circuit(circ, cpath));
  1188. apconn->cpath_layer = cpath;
  1189. } else { /* use the last hop in the circuit */
  1190. tor_assert(circ->cpath);
  1191. tor_assert(circ->cpath->prev);
  1192. tor_assert(circ->cpath->prev->state == CPATH_STATE_OPEN);
  1193. apconn->cpath_layer = circ->cpath->prev;
  1194. }
  1195. }
  1196. /** If an exit wasn't specifically chosen, save the history for future
  1197. * use. */
  1198. static void
  1199. consider_recording_trackhost(edge_connection_t *conn, origin_circuit_t *circ)
  1200. {
  1201. int found_needle = 0;
  1202. or_options_t *options = get_options();
  1203. size_t len;
  1204. char *new_address;
  1205. char fp[HEX_DIGEST_LEN+1];
  1206. /* Search the addressmap for this conn's destination. */
  1207. /* If he's not in the address map.. */
  1208. if (!options->TrackHostExits ||
  1209. addressmap_have_mapping(conn->socks_request->address,
  1210. options->TrackHostExitsExpire))
  1211. return; /* nothing to track, or already mapped */
  1212. SMARTLIST_FOREACH(options->TrackHostExits, const char *, cp, {
  1213. if (cp[0] == '.') { /* match end */
  1214. if (cp[1] == '\0' ||
  1215. !strcasecmpend(conn->socks_request->address, cp) ||
  1216. !strcasecmp(conn->socks_request->address, &cp[1]))
  1217. found_needle = 1;
  1218. } else if (strcasecmp(cp, conn->socks_request->address) == 0) {
  1219. found_needle = 1;
  1220. }
  1221. });
  1222. if (!found_needle || !circ->build_state->chosen_exit)
  1223. return;
  1224. /* write down the fingerprint of the chosen exit, not the nickname,
  1225. * because the chosen exit might not be named. */
  1226. base16_encode(fp, sizeof(fp),
  1227. circ->build_state->chosen_exit->identity_digest, DIGEST_LEN);
  1228. /* Add this exit/hostname pair to the addressmap. */
  1229. len = strlen(conn->socks_request->address) + 1 /* '.' */ +
  1230. strlen(fp) + 1 /* '.' */ +
  1231. strlen("exit") + 1 /* '\0' */;
  1232. new_address = tor_malloc(len);
  1233. tor_snprintf(new_address, len, "%s.%s.exit",
  1234. conn->socks_request->address, fp);
  1235. addressmap_register(conn->socks_request->address, new_address,
  1236. time(NULL) + options->TrackHostExitsExpire,
  1237. ADDRMAPSRC_TRACKEXIT);
  1238. }
  1239. /** Attempt to attach the connection <b>conn</b> to <b>circ</b>, and send a
  1240. * begin or resolve cell as appropriate. Return values are as for
  1241. * connection_ap_handshake_attach_circuit. The stream will exit from the hop
  1242. * indicated by <b>cpath</b>, or from the last hop in circ's cpath if
  1243. * <b>cpath</b> is NULL. */
  1244. int
  1245. connection_ap_handshake_attach_chosen_circuit(edge_connection_t *conn,
  1246. origin_circuit_t *circ,
  1247. crypt_path_t *cpath)
  1248. {
  1249. tor_assert(conn);
  1250. tor_assert(conn->_base.state == AP_CONN_STATE_CIRCUIT_WAIT ||
  1251. conn->_base.state == AP_CONN_STATE_CONTROLLER_WAIT);
  1252. tor_assert(conn->socks_request);
  1253. tor_assert(circ);
  1254. tor_assert(circ->_base.state == CIRCUIT_STATE_OPEN);
  1255. conn->_base.state = AP_CONN_STATE_CIRCUIT_WAIT;
  1256. if (!circ->_base.timestamp_dirty)
  1257. circ->_base.timestamp_dirty = time(NULL);
  1258. link_apconn_to_circ(conn, circ, cpath);
  1259. tor_assert(conn->socks_request);
  1260. if (conn->socks_request->command == SOCKS_COMMAND_CONNECT) {
  1261. if (!conn->use_begindir)
  1262. consider_recording_trackhost(conn, circ);
  1263. if (connection_ap_handshake_send_begin(conn) < 0)
  1264. return -1;
  1265. } else {
  1266. if (connection_ap_handshake_send_resolve(conn) < 0)
  1267. return -1;
  1268. }
  1269. return 1;
  1270. }
  1271. /** Try to find a safe live circuit for CONN_TYPE_AP connection conn. If
  1272. * we don't find one: if conn cannot be handled by any known nodes,
  1273. * warn and return -1 (conn needs to die, and is maybe already marked);
  1274. * else launch new circuit (if necessary) and return 0.
  1275. * Otherwise, associate conn with a safe live circuit, do the
  1276. * right next step, and return 1.
  1277. */
  1278. /* XXXX this function should mark for close whenever it returns -1;
  1279. * its callers shouldn't have to worry about that. */
  1280. int
  1281. connection_ap_handshake_attach_circuit(edge_connection_t *conn)
  1282. {
  1283. int retval;
  1284. int conn_age;
  1285. int want_onehop;
  1286. tor_assert(conn);
  1287. tor_assert(conn->_base.state == AP_CONN_STATE_CIRCUIT_WAIT);
  1288. tor_assert(conn->socks_request);
  1289. want_onehop = conn->want_onehop;
  1290. conn_age = (int)(time(NULL) - conn->_base.timestamp_created);
  1291. if (conn_age >= get_options()->SocksTimeout) {
  1292. int severity = (tor_addr_is_null(&conn->_base.addr) && !conn->_base.port) ?
  1293. LOG_INFO : LOG_NOTICE;
  1294. log_fn(severity, LD_APP,
  1295. "Tried for %d seconds to get a connection to %s:%d. Giving up.",
  1296. conn_age, safe_str(conn->socks_request->address),
  1297. conn->socks_request->port);
  1298. return -1;
  1299. }
  1300. if (!connection_edge_is_rendezvous_stream(conn)) { /* we're a general conn */
  1301. origin_circuit_t *circ=NULL;
  1302. if (conn->chosen_exit_name) {
  1303. routerinfo_t *router = router_get_by_nickname(conn->chosen_exit_name, 1);
  1304. int opt = conn->chosen_exit_optional;
  1305. if (!router && !want_onehop) {
  1306. /* We ran into this warning when trying to extend a circuit to a
  1307. * hidden service directory for which we didn't have a router
  1308. * descriptor. See flyspray task 767 for more details. We should
  1309. * keep this in mind when deciding to use BEGIN_DIR cells for other
  1310. * directory requests as well. -KL*/
  1311. log_fn(opt ? LOG_INFO : LOG_WARN, LD_APP,
  1312. "Requested exit point '%s' is not known. %s.",
  1313. conn->chosen_exit_name, opt ? "Trying others" : "Closing");
  1314. if (opt) {
  1315. conn->chosen_exit_optional = 0;
  1316. tor_free(conn->chosen_exit_name);
  1317. return 0;
  1318. }
  1319. return -1;
  1320. }
  1321. if (router && !connection_ap_can_use_exit(conn, router)) {
  1322. log_fn(opt ? LOG_INFO : LOG_WARN, LD_APP,
  1323. "Requested exit point '%s' would refuse request. %s.",
  1324. conn->chosen_exit_name, opt ? "Trying others" : "Closing");
  1325. if (opt) {
  1326. conn->chosen_exit_optional = 0;
  1327. tor_free(conn->chosen_exit_name);
  1328. return 0;
  1329. }
  1330. return -1;
  1331. }
  1332. }
  1333. /* find the circuit that we should use, if there is one. */
  1334. retval = circuit_get_open_circ_or_launch(
  1335. conn, CIRCUIT_PURPOSE_C_GENERAL, &circ);
  1336. if (retval < 1) // XXX021 if we totally fail, this still returns 0 -RD
  1337. return retval;
  1338. log_debug(LD_APP|LD_CIRC,
  1339. "Attaching apconn to circ %d (stream %d sec old).",
  1340. circ->_base.n_circ_id, conn_age);
  1341. /* print the circ's path, so people can figure out which circs are
  1342. * sucking. */
  1343. circuit_log_path(LOG_INFO,LD_APP|LD_CIRC,circ);
  1344. /* We have found a suitable circuit for our conn. Hurray. */
  1345. return connection_ap_handshake_attach_chosen_circuit(conn, circ, NULL);
  1346. } else { /* we're a rendezvous conn */
  1347. origin_circuit_t *rendcirc=NULL, *introcirc=NULL;
  1348. tor_assert(!conn->cpath_layer);
  1349. /* start by finding a rendezvous circuit for us */
  1350. retval = circuit_get_open_circ_or_launch(
  1351. conn, CIRCUIT_PURPOSE_C_REND_JOINED, &rendcirc);
  1352. if (retval < 0) return -1; /* failed */
  1353. if (retval > 0) {
  1354. tor_assert(rendcirc);
  1355. /* one is already established, attach */
  1356. log_info(LD_REND,
  1357. "rend joined circ %d already here. attaching. "
  1358. "(stream %d sec old)",
  1359. rendcirc->_base.n_circ_id, conn_age);
  1360. /* Mark rendezvous circuits as 'newly dirty' every time you use
  1361. * them, since the process of rebuilding a rendezvous circ is so
  1362. * expensive. There is a tradeoff between linkability and
  1363. * feasibility, at this point.
  1364. */
  1365. rendcirc->_base.timestamp_dirty = time(NULL);
  1366. link_apconn_to_circ(conn, rendcirc, NULL);
  1367. if (connection_ap_handshake_send_begin(conn) < 0)
  1368. return 0; /* already marked, let them fade away */
  1369. return 1;
  1370. }
  1371. if (rendcirc && (rendcirc->_base.purpose ==
  1372. CIRCUIT_PURPOSE_C_REND_READY_INTRO_ACKED)) {
  1373. log_info(LD_REND,
  1374. "pending-join circ %d already here, with intro ack. "
  1375. "Stalling. (stream %d sec old)",
  1376. rendcirc->_base.n_circ_id, conn_age);
  1377. return 0;
  1378. }
  1379. /* it's on its way. find an intro circ. */
  1380. retval = circuit_get_open_circ_or_launch(
  1381. conn, CIRCUIT_PURPOSE_C_INTRODUCE_ACK_WAIT, &introcirc);
  1382. if (retval < 0) return -1; /* failed */
  1383. if (retval > 0) {
  1384. /* one has already sent the intro. keep waiting. */
  1385. circuit_t *c = NULL;
  1386. tor_assert(introcirc);
  1387. log_info(LD_REND, "Intro circ %d present and awaiting ack (rend %d). "
  1388. "Stalling. (stream %d sec old)",
  1389. introcirc->_base.n_circ_id,
  1390. rendcirc ? rendcirc->_base.n_circ_id : 0,
  1391. conn_age);
  1392. /* abort parallel intro circs, if any */
  1393. for (c = global_circuitlist; c; c = c->next) {
  1394. if (c->purpose == CIRCUIT_PURPOSE_C_INTRODUCING &&
  1395. !c->marked_for_close && CIRCUIT_IS_ORIGIN(c)) {
  1396. origin_circuit_t *oc = TO_ORIGIN_CIRCUIT(c);
  1397. if (oc->rend_data &&
  1398. !rend_cmp_service_ids(conn->rend_data->onion_address,
  1399. oc->rend_data->onion_address)) {
  1400. log_info(LD_REND|LD_CIRC, "Closing introduction circuit that we "
  1401. "built in parallel.");
  1402. circuit_mark_for_close(c, END_CIRC_REASON_TIMEOUT);
  1403. }
  1404. }
  1405. }
  1406. return 0;
  1407. }
  1408. /* now rendcirc and introcirc are each either undefined or not finished */
  1409. if (rendcirc && introcirc &&
  1410. rendcirc->_base.purpose == CIRCUIT_PURPOSE_C_REND_READY) {
  1411. log_info(LD_REND,
  1412. "ready rend circ %d already here (no intro-ack yet on "
  1413. "intro %d). (stream %d sec old)",
  1414. rendcirc->_base.n_circ_id,
  1415. introcirc->_base.n_circ_id, conn_age);
  1416. tor_assert(introcirc->_base.purpose == CIRCUIT_PURPOSE_C_INTRODUCING);
  1417. if (introcirc->_base.state == CIRCUIT_STATE_OPEN) {
  1418. log_info(LD_REND,"found open intro circ %d (rend %d); sending "
  1419. "introduction. (stream %d sec old)",
  1420. introcirc->_base.n_circ_id, rendcirc->_base.n_circ_id,
  1421. conn_age);
  1422. switch (rend_client_send_introduction(introcirc, rendcirc)) {
  1423. case 0: /* success */
  1424. rendcirc->_base.timestamp_dirty = time(NULL);
  1425. introcirc->_base.timestamp_dirty = time(NULL);
  1426. assert_circuit_ok(TO_CIRCUIT(rendcirc));
  1427. assert_circuit_ok(TO_CIRCUIT(introcirc));
  1428. return 0;
  1429. case -1: /* transient error */
  1430. return 0;
  1431. case -2: /* permanent error */
  1432. return -1;
  1433. default: /* oops */
  1434. tor_fragile_assert();
  1435. return -1;
  1436. }
  1437. }
  1438. }
  1439. log_info(LD_REND, "Intro (%d) and rend (%d) circs are not both ready. "
  1440. "Stalling conn. (%d sec old)",
  1441. introcirc ? introcirc->_base.n_circ_id : 0,
  1442. rendcirc ? rendcirc->_base.n_circ_id : 0, conn_age);
  1443. return 0;
  1444. }
  1445. }