circuituse.c 43 KB

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