circuituse.c 43 KB

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