circuituse.c 45 KB

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