circuituse.c 50 KB

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