circuituse.c 49 KB

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