circuituse.c 46 KB

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