circuituse.c 42 KB

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