circuituse.c 47 KB

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