circuituse.c 41 KB

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