circuituse.c 51 KB

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