circuituse.c 31 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887
  1. /* Copyright 2001 Matej Pfajfar.
  2. * Copyright 2001-2004 Roger Dingledine.
  3. * Copyright 2004 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, 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 60
  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 circuit_is_acceptable(circuit_t *circ,
  24. connection_t *conn,
  25. int must_be_open,
  26. uint8_t purpose,
  27. time_t now)
  28. {
  29. routerinfo_t *exitrouter;
  30. if (!CIRCUIT_IS_ORIGIN(circ))
  31. return 0; /* this circ doesn't start at us */
  32. if (must_be_open && (circ->state != CIRCUIT_STATE_OPEN || !circ->n_conn))
  33. return 0; /* ignore non-open circs */
  34. if (circ->marked_for_close)
  35. return 0;
  36. /* if this circ isn't our purpose, skip. */
  37. if (purpose == CIRCUIT_PURPOSE_C_REND_JOINED && !must_be_open) {
  38. if (circ->purpose != CIRCUIT_PURPOSE_C_ESTABLISH_REND &&
  39. circ->purpose != CIRCUIT_PURPOSE_C_REND_READY &&
  40. circ->purpose != CIRCUIT_PURPOSE_C_REND_READY_INTRO_ACKED &&
  41. circ->purpose != CIRCUIT_PURPOSE_C_REND_JOINED)
  42. return 0;
  43. } else if (purpose == CIRCUIT_PURPOSE_C_INTRODUCE_ACK_WAIT && !must_be_open) {
  44. if (circ->purpose != CIRCUIT_PURPOSE_C_INTRODUCING &&
  45. circ->purpose != CIRCUIT_PURPOSE_C_INTRODUCE_ACK_WAIT)
  46. return 0;
  47. } else {
  48. if (purpose != circ->purpose)
  49. return 0;
  50. }
  51. if (purpose == CIRCUIT_PURPOSE_C_GENERAL)
  52. if (circ->timestamp_dirty &&
  53. circ->timestamp_dirty+get_options()->NewCircuitPeriod <= now)
  54. return 0;
  55. if (conn) {
  56. /* decide if this circ is suitable for this conn */
  57. /* for rend circs, circ->cpath->prev is not the last router in the
  58. * circuit, it's the magical extra bob hop. so just check the nickname
  59. * of the one we meant to finish at.
  60. */
  61. exitrouter = router_get_by_digest(circ->build_state->chosen_exit_digest);
  62. if (!exitrouter) {
  63. log_fn(LOG_INFO,"Skipping broken circ (exit router vanished)");
  64. return 0; /* this circuit is screwed and doesn't know it yet */
  65. }
  66. if (conn->socks_request &&
  67. conn->socks_request->command == SOCKS_COMMAND_RESOLVE) {
  68. /* 0.0.8 servers have buggy resolve support. */
  69. if (!tor_version_as_new_as(exitrouter->platform, "0.0.9pre1"))
  70. return 0;
  71. } else if (purpose == CIRCUIT_PURPOSE_C_GENERAL) {
  72. if (!connection_ap_can_use_exit(conn, exitrouter)) {
  73. /* can't exit from this router */
  74. return 0;
  75. }
  76. } else { /* not general */
  77. if (rend_cmp_service_ids(conn->rend_query, circ->rend_query) &&
  78. (circ->rend_query[0] || purpose != CIRCUIT_PURPOSE_C_REND_JOINED)) {
  79. /* this circ is not for this conn, and it's not suitable
  80. * for cannibalizing either */
  81. return 0;
  82. }
  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 circuit_is_better(circuit_t *a, circuit_t *b, uint8_t purpose)
  91. {
  92. switch (purpose) {
  93. case CIRCUIT_PURPOSE_C_GENERAL:
  94. /* if it's used but less dirty it's best;
  95. * else if it's more recently created it's best
  96. */
  97. if (b->timestamp_dirty) {
  98. if (a->timestamp_dirty &&
  99. a->timestamp_dirty > b->timestamp_dirty)
  100. return 1;
  101. } else {
  102. if (a->timestamp_dirty ||
  103. a->timestamp_created > b->timestamp_created)
  104. return 1;
  105. }
  106. break;
  107. case CIRCUIT_PURPOSE_C_INTRODUCE_ACK_WAIT:
  108. /* the closer it is to ack_wait the better it is */
  109. if (a->purpose > b->purpose)
  110. return 1;
  111. break;
  112. case CIRCUIT_PURPOSE_C_REND_JOINED:
  113. /* the closer it is to rend_joined the better it is */
  114. if (a->purpose > b->purpose)
  115. return 1;
  116. break;
  117. }
  118. return 0;
  119. }
  120. /** Find the best circ that conn can use, preferably one which is
  121. * dirty. Circ must not be too old.
  122. *
  123. * Conn must be defined.
  124. *
  125. * If must_be_open, ignore circs not in CIRCUIT_STATE_OPEN.
  126. *
  127. * circ_purpose specifies what sort of circuit we must have.
  128. * It can be C_GENERAL, C_INTRODUCE_ACK_WAIT, or C_REND_JOINED.
  129. *
  130. * If it's REND_JOINED and must_be_open==0, then return the closest
  131. * rendezvous-purposed circuit that you can find.
  132. *
  133. * If it's INTRODUCE_ACK_WAIT and must_be_open==0, then return the
  134. * closest introduce-purposed circuit that you can find.
  135. */
  136. static circuit_t *
  137. circuit_get_best(connection_t *conn, int must_be_open, uint8_t purpose)
  138. {
  139. circuit_t *circ, *best=NULL;
  140. time_t now = time(NULL);
  141. tor_assert(conn);
  142. tor_assert(purpose == CIRCUIT_PURPOSE_C_GENERAL ||
  143. purpose == CIRCUIT_PURPOSE_C_INTRODUCE_ACK_WAIT ||
  144. purpose == CIRCUIT_PURPOSE_C_REND_JOINED);
  145. for (circ=global_circuitlist;circ;circ = circ->next) {
  146. if (!circuit_is_acceptable(circ,conn,must_be_open,purpose,now))
  147. continue;
  148. /* now this is an acceptable circ to hand back. but that doesn't
  149. * mean it's the *best* circ to hand back. try to decide.
  150. */
  151. if (!best || circuit_is_better(circ,best,purpose))
  152. best = circ;
  153. }
  154. return best;
  155. }
  156. /** Circuits that were born at the end of their second might be expired
  157. * after 30.1 seconds; circuits born at the beginning might be expired
  158. * after closer to 31 seconds.
  159. */
  160. #define MIN_SECONDS_BEFORE_EXPIRING_CIRC 30
  161. /** Close all circuits that start at us, aren't open, and were born
  162. * at least MIN_SECONDS_BEFORE_EXPIRING_CIRC seconds ago.
  163. */
  164. void circuit_expire_building(time_t now) {
  165. circuit_t *victim, *circ = global_circuitlist;
  166. while (circ) {
  167. victim = circ;
  168. circ = circ->next;
  169. if (!CIRCUIT_IS_ORIGIN(victim))
  170. continue; /* didn't originate here */
  171. if (victim->marked_for_close)
  172. continue; /* don't mess with marked circs */
  173. if (victim->timestamp_created + MIN_SECONDS_BEFORE_EXPIRING_CIRC > now)
  174. continue; /* it's young still, don't mess with it */
  175. /* some debug logs, to help track bugs */
  176. if (victim->purpose >= CIRCUIT_PURPOSE_C_INTRODUCING &&
  177. victim->purpose <= CIRCUIT_PURPOSE_C_REND_READY_INTRO_ACKED) {
  178. if (!victim->timestamp_dirty)
  179. log_fn(LOG_DEBUG,"Considering %sopen purp %d to %s (circid %d). (clean).",
  180. victim->state == CIRCUIT_STATE_OPEN ? "" : "non",
  181. victim->purpose, victim->build_state->chosen_exit_name,
  182. victim->n_circ_id);
  183. else
  184. log_fn(LOG_DEBUG,"Considering %sopen purp %d to %s (circid %d). %d secs since dirty.",
  185. victim->state == CIRCUIT_STATE_OPEN ? "" : "non",
  186. victim->purpose, victim->build_state->chosen_exit_name,
  187. victim->n_circ_id,
  188. (int)(now - victim->timestamp_dirty));
  189. }
  190. /* if circ is !open, or if it's open but purpose is a non-finished
  191. * intro or rend, then mark it for close */
  192. if (victim->state != CIRCUIT_STATE_OPEN ||
  193. victim->purpose == CIRCUIT_PURPOSE_C_ESTABLISH_REND ||
  194. victim->purpose == CIRCUIT_PURPOSE_C_INTRODUCING ||
  195. victim->purpose == CIRCUIT_PURPOSE_S_ESTABLISH_INTRO ||
  196. /* it's a rend_ready circ, but it's already picked a query */
  197. (victim->purpose == CIRCUIT_PURPOSE_C_REND_READY &&
  198. victim->rend_query[0]) ||
  199. /* c_rend_ready circs measure age since timestamp_dirty,
  200. * because that's set when they switch purposes
  201. */
  202. /* rend and intro circs become dirty each time they
  203. * make an introduction attempt. so timestamp_dirty
  204. * will reflect the time since the last attempt.
  205. */
  206. ((victim->purpose == CIRCUIT_PURPOSE_C_REND_READY ||
  207. victim->purpose == CIRCUIT_PURPOSE_C_REND_READY_INTRO_ACKED ||
  208. victim->purpose == CIRCUIT_PURPOSE_C_INTRODUCE_ACK_WAIT) &&
  209. victim->timestamp_dirty + MIN_SECONDS_BEFORE_EXPIRING_CIRC > now)) {
  210. if (victim->n_conn)
  211. log_fn(LOG_INFO,"Abandoning circ %s:%d:%d (state %d:%s, purpose %d)",
  212. victim->n_conn->address, victim->n_port, victim->n_circ_id,
  213. victim->state, circuit_state_to_string[victim->state], victim->purpose);
  214. else
  215. log_fn(LOG_INFO,"Abandoning circ %d (state %d:%s, purpose %d)", victim->n_circ_id,
  216. victim->state, circuit_state_to_string[victim->state], victim->purpose);
  217. circuit_log_path(LOG_INFO,victim);
  218. circuit_mark_for_close(victim);
  219. }
  220. }
  221. }
  222. /** How many circuits do we want simultaneously in-progress to handle
  223. * a given stream?
  224. */
  225. #define MIN_CIRCUITS_HANDLING_STREAM 2
  226. /** Return 1 if at least MIN_CIRCUITS_HANDLING_STREAM non-open
  227. * general-purpose circuits will have an acceptable exit node for
  228. * conn. Else return 0.
  229. */
  230. int circuit_stream_is_being_handled(connection_t *conn) {
  231. circuit_t *circ;
  232. routerinfo_t *exitrouter;
  233. int num=0;
  234. time_t now = time(NULL);
  235. for (circ=global_circuitlist;circ;circ = circ->next) {
  236. if (CIRCUIT_IS_ORIGIN(circ) &&
  237. circ->state != CIRCUIT_STATE_OPEN &&
  238. !circ->marked_for_close &&
  239. circ->purpose == CIRCUIT_PURPOSE_C_GENERAL &&
  240. (!circ->timestamp_dirty ||
  241. circ->timestamp_dirty + get_options()->NewCircuitPeriod < now)) {
  242. exitrouter = router_get_by_digest(circ->build_state->chosen_exit_digest);
  243. if (exitrouter && connection_ap_can_use_exit(conn, exitrouter))
  244. if (++num >= MIN_CIRCUITS_HANDLING_STREAM)
  245. return 1;
  246. }
  247. }
  248. return 0;
  249. }
  250. /** Build a new test circuit every 5 minutes */
  251. #define TESTING_CIRCUIT_INTERVAL 300
  252. /** This function is called once a second. Its job is to make sure
  253. * all services we offer have enough circuits available. Some
  254. * services just want enough circuits for current tasks, whereas
  255. * others want a minimum set of idle circuits hanging around.
  256. */
  257. void circuit_build_needed_circs(time_t now) {
  258. static long time_to_new_circuit = 0;
  259. circuit_t *circ;
  260. /* launch a new circ for any pending streams that need one */
  261. connection_ap_attach_pending();
  262. /* make sure any hidden services have enough intro points */
  263. if (has_fetched_directory)
  264. rend_services_introduce();
  265. circ = circuit_get_youngest_clean_open(CIRCUIT_PURPOSE_C_GENERAL);
  266. if (time_to_new_circuit < now) {
  267. circuit_reset_failure_count(1);
  268. time_to_new_circuit = now + get_options()->NewCircuitPeriod;
  269. if (proxy_mode(get_options()))
  270. client_dns_clean();
  271. circuit_expire_old_circuits();
  272. if (get_options()->RunTesting &&
  273. circ &&
  274. circ->timestamp_created + TESTING_CIRCUIT_INTERVAL < now) {
  275. log_fn(LOG_INFO,"Creating a new testing circuit.");
  276. circuit_launch_by_identity(CIRCUIT_PURPOSE_C_GENERAL, NULL);
  277. }
  278. }
  279. /** How many simultaneous in-progress general-purpose circuits do we
  280. * want to be building at once, if there are no open general-purpose
  281. * circuits?
  282. */
  283. #define CIRCUIT_MIN_BUILDING_GENERAL 5
  284. /* if there's no open circ, and less than 5 are on the way,
  285. * go ahead and try another. */
  286. if (!circ && circuit_count_building(CIRCUIT_PURPOSE_C_GENERAL)
  287. < CIRCUIT_MIN_BUILDING_GENERAL) {
  288. circuit_launch_by_identity(CIRCUIT_PURPOSE_C_GENERAL, NULL);
  289. }
  290. /* XXX count idle rendezvous circs and build more */
  291. }
  292. /** If the stream <b>conn</b> is a member of any of the linked
  293. * lists of <b>circ</b>, then remove it from the list.
  294. */
  295. void circuit_detach_stream(circuit_t *circ, connection_t *conn) {
  296. connection_t *prevconn;
  297. tor_assert(circ);
  298. tor_assert(conn);
  299. conn->cpath_layer = NULL; /* make sure we don't keep a stale pointer */
  300. if (conn == circ->p_streams) {
  301. circ->p_streams = conn->next_stream;
  302. return;
  303. }
  304. if (conn == circ->n_streams) {
  305. circ->n_streams = conn->next_stream;
  306. return;
  307. }
  308. if (conn == circ->resolving_streams) {
  309. circ->resolving_streams = conn->next_stream;
  310. return;
  311. }
  312. for (prevconn = circ->p_streams;
  313. prevconn && prevconn->next_stream && prevconn->next_stream != conn;
  314. prevconn = prevconn->next_stream)
  315. ;
  316. if (prevconn && prevconn->next_stream) {
  317. prevconn->next_stream = conn->next_stream;
  318. return;
  319. }
  320. for (prevconn = circ->n_streams;
  321. prevconn && prevconn->next_stream && prevconn->next_stream != conn;
  322. prevconn = prevconn->next_stream)
  323. ;
  324. if (prevconn && prevconn->next_stream) {
  325. prevconn->next_stream = conn->next_stream;
  326. return;
  327. }
  328. for (prevconn = circ->resolving_streams;
  329. prevconn && prevconn->next_stream && prevconn->next_stream != conn;
  330. prevconn = prevconn->next_stream)
  331. ;
  332. if (prevconn && prevconn->next_stream) {
  333. prevconn->next_stream = conn->next_stream;
  334. return;
  335. }
  336. log_fn(LOG_ERR,"edge conn not in circuit's list?");
  337. tor_assert(0); /* should never get here */
  338. }
  339. /** Notify the global circuit list that <b>conn</b> is about to be
  340. * removed and then freed.
  341. *
  342. * If it's an OR conn, then mark-for-close all the circuits that use
  343. * that conn.
  344. *
  345. * If it's an edge conn, then detach it from its circ, so we don't
  346. * try to reference it later.
  347. */
  348. void circuit_about_to_close_connection(connection_t *conn) {
  349. /* currently, we assume it's too late to flush conn's buf here.
  350. * down the road, maybe we'll consider that eof doesn't mean can't-write
  351. */
  352. circuit_t *circ;
  353. switch (conn->type) {
  354. case CONN_TYPE_OR:
  355. if (conn->state != OR_CONN_STATE_OPEN) {
  356. /* Inform any pending (not attached) circs that they should give up. */
  357. circuit_n_conn_done(conn, 0);
  358. }
  359. /* Now close all the attached circuits on it. */
  360. while ((circ = circuit_get_by_conn(conn))) {
  361. if (circ->n_conn == conn) /* it's closing in front of us */
  362. circ->n_conn = NULL;
  363. if (circ->p_conn == conn) /* it's closing behind us */
  364. circ->p_conn = NULL;
  365. circuit_mark_for_close(circ);
  366. }
  367. return;
  368. case CONN_TYPE_AP:
  369. case CONN_TYPE_EXIT:
  370. /* It's an edge conn. Need to remove it from the linked list of
  371. * conn's for this circuit. Confirm that 'end' relay command has
  372. * been sent. But don't kill the circuit.
  373. */
  374. circ = circuit_get_by_conn(conn);
  375. if (!circ)
  376. return;
  377. circuit_detach_stream(circ, conn);
  378. } /* end switch */
  379. }
  380. /** Don't keep more than 10 unused open circuits around. */
  381. #define MAX_UNUSED_OPEN_CIRCUITS 10
  382. /** Find each circuit that has been dirty for too long, and has
  383. * no streams on it: mark it for close.
  384. *
  385. * Also, if there are more than MAX_UNUSED_OPEN_CIRCUITS open and
  386. * unused circuits, then mark the excess circs for close.
  387. */
  388. static void
  389. circuit_expire_old_circuits(void)
  390. {
  391. circuit_t *circ;
  392. time_t now = time(NULL);
  393. smartlist_t *unused_open_circs;
  394. int i;
  395. unused_open_circs = smartlist_create();
  396. for (circ = global_circuitlist; circ; circ = circ->next) {
  397. if (circ->marked_for_close)
  398. continue;
  399. /* If the circuit has been dirty for too long, and there are no streams
  400. * on it, mark it for close.
  401. */
  402. if (circ->timestamp_dirty &&
  403. circ->timestamp_dirty + get_options()->NewCircuitPeriod < now &&
  404. !circ->p_conn && /* we're the origin */
  405. !circ->p_streams /* nothing attached */ ) {
  406. log_fn(LOG_DEBUG,"Closing n_circ_id %d (dirty %d secs ago, purp %d)",circ->n_circ_id,
  407. (int)(now - circ->timestamp_dirty), circ->purpose);
  408. /* (only general and purpose_c circs can get dirty) */
  409. tor_assert(!circ->n_streams);
  410. tor_assert(circ->purpose <= CIRCUIT_PURPOSE_C_REND_JOINED);
  411. circuit_mark_for_close(circ);
  412. } else if (!circ->timestamp_dirty && CIRCUIT_IS_ORIGIN(circ) &&
  413. circ->state == CIRCUIT_STATE_OPEN &&
  414. circ->purpose == CIRCUIT_PURPOSE_C_GENERAL) {
  415. /* Also, gather a list of open unused general circuits that we created.
  416. * Because we add elements to the front of global_circuitlist,
  417. * the last elements of unused_open_circs will be the oldest
  418. * ones.
  419. */
  420. smartlist_add(unused_open_circs, circ);
  421. }
  422. }
  423. for (i = MAX_UNUSED_OPEN_CIRCUITS; i < smartlist_len(unused_open_circs); ++i) {
  424. circuit_t *circ = smartlist_get(unused_open_circs, i);
  425. log_fn(LOG_DEBUG,"Expiring excess clean circ (n_circ_id %d, purp %d)",
  426. circ->n_circ_id, circ->purpose);
  427. circuit_mark_for_close(circ);
  428. }
  429. smartlist_free(unused_open_circs);
  430. }
  431. /** The circuit <b>circ</b> has just become open. Take the next
  432. * step: for rendezvous circuits, we pass circ to the appropriate
  433. * function in rendclient or rendservice. For general circuits, we
  434. * call connection_ap_attach_pending, which looks for pending streams
  435. * that could use circ.
  436. */
  437. void circuit_has_opened(circuit_t *circ) {
  438. control_event_circuit_status(circ, CIRC_EVENT_BUILT);
  439. switch (circ->purpose) {
  440. case CIRCUIT_PURPOSE_C_ESTABLISH_REND:
  441. rend_client_rendcirc_has_opened(circ);
  442. break;
  443. case CIRCUIT_PURPOSE_C_INTRODUCING:
  444. rend_client_introcirc_has_opened(circ);
  445. break;
  446. case CIRCUIT_PURPOSE_C_GENERAL:
  447. /* Tell any AP connections that have been waiting for a new
  448. * circuit that one is ready. */
  449. connection_ap_attach_pending();
  450. break;
  451. case CIRCUIT_PURPOSE_S_ESTABLISH_INTRO:
  452. /* at Bob, waiting for introductions */
  453. rend_service_intro_has_opened(circ);
  454. break;
  455. case CIRCUIT_PURPOSE_S_CONNECT_REND:
  456. /* at Bob, connecting to rend point */
  457. rend_service_rendezvous_has_opened(circ);
  458. break;
  459. default:
  460. log_fn(LOG_ERR,"unhandled purpose %d",circ->purpose);
  461. tor_assert(0);
  462. }
  463. }
  464. /*~ Called whenever a circuit could not be successfully built.
  465. */
  466. void circuit_build_failed(circuit_t *circ) {
  467. /* we should examine circ and see if it failed because of
  468. * the last hop or an earlier hop. then use this info below.
  469. */
  470. int failed_at_last_hop = 0;
  471. /* If the last hop isn't open, and the second-to-last is, we failed
  472. * at the last hop. */
  473. if (circ->cpath &&
  474. circ->cpath->prev->state != CPATH_STATE_OPEN &&
  475. circ->cpath->prev->prev->state == CPATH_STATE_OPEN) {
  476. failed_at_last_hop = 1;
  477. }
  478. switch (circ->purpose) {
  479. case CIRCUIT_PURPOSE_C_GENERAL:
  480. if (circ->state != CIRCUIT_STATE_OPEN) {
  481. /* If we never built the circuit, note it as a failure. */
  482. /* Note that we can't just check circ->cpath here, because if
  483. * circuit-building failed immediately, it won't be set yet. */
  484. circuit_increment_failure_count();
  485. }
  486. break;
  487. case CIRCUIT_PURPOSE_S_ESTABLISH_INTRO:
  488. /* at Bob, waiting for introductions */
  489. if (circ->state != CIRCUIT_STATE_OPEN) {
  490. circuit_increment_failure_count();
  491. }
  492. /* no need to care here, because bob will rebuild intro
  493. * points periodically. */
  494. break;
  495. case CIRCUIT_PURPOSE_C_INTRODUCING:
  496. /* at Alice, connecting to intro point */
  497. /* Don't increment failure count, since Bob may have picked
  498. * the introduction point maliciously */
  499. /* Alice will pick a new intro point when this one dies, if
  500. * the stream in question still cares. No need to act here. */
  501. break;
  502. case CIRCUIT_PURPOSE_C_ESTABLISH_REND:
  503. /* at Alice, waiting for Bob */
  504. if (circ->state != CIRCUIT_STATE_OPEN) {
  505. circuit_increment_failure_count();
  506. }
  507. /* Alice will pick a new rend point when this one dies, if
  508. * the stream in question still cares. No need to act here. */
  509. break;
  510. case CIRCUIT_PURPOSE_S_CONNECT_REND:
  511. /* at Bob, connecting to rend point */
  512. /* Don't increment failure count, since Alice may have picked
  513. * the rendezvous point maliciously */
  514. if (failed_at_last_hop) {
  515. log_fn(LOG_INFO,"Couldn't connect to Alice's chosen rend point %s. Sucks to be Alice.", circ->build_state->chosen_exit_name);
  516. } else {
  517. log_fn(LOG_INFO,"Couldn't connect to Alice's chosen rend point %s, because an earlier node failed.",
  518. circ->build_state->chosen_exit_name);
  519. rend_service_relaunch_rendezvous(circ);
  520. }
  521. break;
  522. default:
  523. /* Other cases are impossible, since this function is only called with
  524. * unbuilt circuits. */
  525. tor_assert(0);
  526. }
  527. }
  528. /** Number of consecutive failures so far; should only be touched by
  529. * circuit_launch_new and circuit_*_failure_count.
  530. */
  531. static int n_circuit_failures = 0;
  532. static int did_circs_fail_last_period = 0;
  533. /** Don't retry launching a new circuit if we try this many times with no
  534. * success. */
  535. #define MAX_CIRCUIT_FAILURES 5
  536. circuit_t *circuit_launch_by_identity(uint8_t purpose, const char *exit_digest)
  537. {
  538. if (!has_fetched_directory) {
  539. log_fn(LOG_DEBUG,"Haven't fetched directory yet; cancelling circuit launch.");
  540. return NULL;
  541. }
  542. if (did_circs_fail_last_period &&
  543. n_circuit_failures > MAX_CIRCUIT_FAILURES) {
  544. /* too many failed circs in a row. don't try. */
  545. // log_fn(LOG_INFO,"%d failures so far, not trying.",n_circuit_failures);
  546. return NULL;
  547. }
  548. /* try a circ. if it fails, circuit_mark_for_close will increment n_circuit_failures */
  549. return circuit_establish_circuit(purpose, exit_digest);
  550. }
  551. /** Launch a new circuit and return a pointer to it. Return NULL if you failed. */
  552. circuit_t *circuit_launch_by_nickname(uint8_t purpose, const char *exit_nickname)
  553. {
  554. const char *digest = NULL;
  555. if (exit_nickname) {
  556. routerinfo_t *r = router_get_by_nickname(exit_nickname);
  557. if (!r) {
  558. log_fn(LOG_WARN, "No such OR as '%s'", exit_nickname);
  559. return NULL;
  560. }
  561. digest = r->identity_digest;
  562. }
  563. return circuit_launch_by_identity(purpose, digest);
  564. }
  565. /** Record another failure at opening a general circuit. When we have
  566. * too many, we'll stop trying for the remainder of this minute.
  567. */
  568. static void circuit_increment_failure_count(void) {
  569. ++n_circuit_failures;
  570. log_fn(LOG_DEBUG,"n_circuit_failures now %d.",n_circuit_failures);
  571. }
  572. /** Reset the failure count for opening general circuits. This means
  573. * we will try MAX_CIRCUIT_FAILURES times more (if necessary) before
  574. * stopping again.
  575. */
  576. void circuit_reset_failure_count(int timeout) {
  577. if (timeout && n_circuit_failures > MAX_CIRCUIT_FAILURES)
  578. did_circs_fail_last_period = 1;
  579. else
  580. did_circs_fail_last_period = 0;
  581. n_circuit_failures = 0;
  582. }
  583. /** Find an open circ that we're happy with: return 1. If there isn't
  584. * one, and there isn't one on the way, launch one and return 0. If it
  585. * will never work, return -1.
  586. *
  587. * Write the found or in-progress or launched circ into *circp.
  588. */
  589. static int
  590. circuit_get_open_circ_or_launch(connection_t *conn,
  591. uint8_t desired_circuit_purpose,
  592. circuit_t **circp) {
  593. circuit_t *circ;
  594. uint32_t addr;
  595. int is_resolve;
  596. tor_assert(conn);
  597. tor_assert(circp);
  598. tor_assert(conn->state == AP_CONN_STATE_CIRCUIT_WAIT);
  599. is_resolve = conn->socks_request->command == SOCKS_COMMAND_RESOLVE;
  600. circ = circuit_get_best(conn, 1, desired_circuit_purpose);
  601. if (circ) {
  602. *circp = circ;
  603. return 1; /* we're happy */
  604. }
  605. /* Do we need to check exit policy? */
  606. if (!is_resolve && !connection_edge_is_rendezvous_stream(conn)) {
  607. addr = client_dns_lookup_entry(conn->socks_request->address);
  608. if (router_exit_policy_all_routers_reject(addr, conn->socks_request->port)) {
  609. log_fn(LOG_WARN,"No Tor server exists that allows exit to %s:%d. Rejecting.",
  610. conn->socks_request->address, conn->socks_request->port);
  611. return -1;
  612. }
  613. }
  614. /* is one already on the way? */
  615. circ = circuit_get_best(conn, 0, desired_circuit_purpose);
  616. if (!circ) {
  617. char *exitname=NULL;
  618. uint8_t new_circ_purpose;
  619. if (desired_circuit_purpose == CIRCUIT_PURPOSE_C_INTRODUCE_ACK_WAIT) {
  620. /* need to pick an intro point */
  621. exitname = rend_client_get_random_intro(conn->rend_query);
  622. if (!exitname) {
  623. log_fn(LOG_WARN,"Couldn't get an intro point for '%s'. Closing.",
  624. conn->rend_query);
  625. return -1;
  626. }
  627. if (!router_get_by_nickname(exitname)) {
  628. log_fn(LOG_WARN,"Advertised intro point '%s' is not known. Closing.", exitname);
  629. tor_free(exitname);
  630. return -1;
  631. }
  632. /* XXX if we failed, then refetch the descriptor */
  633. log_fn(LOG_INFO,"Chose %s as intro point for %s.", exitname, conn->rend_query);
  634. }
  635. /* If we have specified a particular exit node for our
  636. * connection, then be sure to open a circuit to that exit node.
  637. */
  638. if(desired_circuit_purpose == CIRCUIT_PURPOSE_C_GENERAL) {
  639. if (conn->chosen_exit_name) {
  640. exitname = tor_strdup(conn->chosen_exit_name);
  641. if(!router_get_by_nickname(exitname)) {
  642. log_fn(LOG_WARN,"Requested exit point '%s' is not known. Closing.", exitname);
  643. tor_free(exitname);
  644. return -1;
  645. }
  646. }
  647. }
  648. if (desired_circuit_purpose == CIRCUIT_PURPOSE_C_REND_JOINED)
  649. new_circ_purpose = CIRCUIT_PURPOSE_C_ESTABLISH_REND;
  650. else if (desired_circuit_purpose == CIRCUIT_PURPOSE_C_INTRODUCE_ACK_WAIT)
  651. new_circ_purpose = CIRCUIT_PURPOSE_C_INTRODUCING;
  652. else
  653. new_circ_purpose = desired_circuit_purpose;
  654. circ = circuit_launch_by_nickname(new_circ_purpose, exitname);
  655. tor_free(exitname);
  656. if (circ &&
  657. desired_circuit_purpose != CIRCUIT_PURPOSE_C_GENERAL) {
  658. /* then write the service_id into circ */
  659. strlcpy(circ->rend_query, conn->rend_query, sizeof(circ->rend_query));
  660. }
  661. }
  662. if (!circ)
  663. log_fn(LOG_INFO,"No safe circuit (purpose %d) ready for edge connection; delaying.",
  664. desired_circuit_purpose);
  665. *circp = circ;
  666. return 0;
  667. }
  668. /** Attach the AP stream <b>apconn</b> to circ's linked list of
  669. * p_streams. Also set apconn's cpath_layer to the last hop in
  670. * circ's cpath.
  671. */
  672. static void link_apconn_to_circ(connection_t *apconn, circuit_t *circ) {
  673. /* add it into the linked list of streams on this circuit */
  674. log_fn(LOG_DEBUG,"attaching new conn to circ. n_circ_id %d.", circ->n_circ_id);
  675. apconn->next_stream = circ->p_streams;
  676. /* assert_connection_ok(conn, time(NULL)); */
  677. circ->p_streams = apconn;
  678. tor_assert(CIRCUIT_IS_ORIGIN(circ));
  679. tor_assert(circ->cpath);
  680. tor_assert(circ->cpath->prev);
  681. tor_assert(circ->cpath->prev->state == CPATH_STATE_OPEN);
  682. apconn->cpath_layer = circ->cpath->prev;
  683. }
  684. /** Try to find a safe live circuit for CONN_TYPE_AP connection conn. If
  685. * we don't find one: if conn cannot be handled by any known nodes,
  686. * warn and return -1 (conn needs to die);
  687. * else launch new circuit (if necessary) and return 0.
  688. * Otherwise, associate conn with a safe live circuit, do the
  689. * right next step, and return 1.
  690. */
  691. int connection_ap_handshake_attach_circuit(connection_t *conn) {
  692. int retval;
  693. int conn_age;
  694. tor_assert(conn);
  695. tor_assert(conn->type == CONN_TYPE_AP);
  696. tor_assert(conn->state == AP_CONN_STATE_CIRCUIT_WAIT);
  697. tor_assert(conn->socks_request);
  698. conn_age = time(NULL) - conn->timestamp_created;
  699. if (conn_age > CONN_AP_MAX_ATTACH_DELAY) {
  700. log_fn(LOG_WARN,"Giving up on unattached conn (%d sec old).", conn_age);
  701. return -1;
  702. }
  703. if (!connection_edge_is_rendezvous_stream(conn)) { /* we're a general conn */
  704. circuit_t *circ=NULL;
  705. /* find the circuit that we should use, if there is one. */
  706. retval = circuit_get_open_circ_or_launch(conn, CIRCUIT_PURPOSE_C_GENERAL, &circ);
  707. if (retval < 1)
  708. return retval;
  709. /* We have found a suitable circuit for our conn. Hurray. */
  710. tor_assert(circ);
  711. log_fn(LOG_DEBUG,"Attaching apconn to general circ %d (stream %d sec old).",
  712. circ->n_circ_id, conn_age);
  713. /* here, print the circ's path. so people can figure out which circs are sucking. */
  714. circuit_log_path(LOG_INFO,circ);
  715. if (!circ->timestamp_dirty)
  716. circ->timestamp_dirty = time(NULL);
  717. link_apconn_to_circ(conn, circ);
  718. tor_assert(conn->socks_request);
  719. if (conn->socks_request->command == SOCKS_COMMAND_CONNECT)
  720. connection_ap_handshake_send_begin(conn, circ);
  721. else
  722. connection_ap_handshake_send_resolve(conn, circ);
  723. return 1;
  724. } else { /* we're a rendezvous conn */
  725. circuit_t *rendcirc=NULL, *introcirc=NULL;
  726. tor_assert(!conn->cpath_layer);
  727. /* start by finding a rendezvous circuit for us */
  728. retval = circuit_get_open_circ_or_launch(conn, CIRCUIT_PURPOSE_C_REND_JOINED, &rendcirc);
  729. if (retval < 0) return -1; /* failed */
  730. if (retval > 0) {
  731. tor_assert(rendcirc);
  732. /* one is already established, attach */
  733. log_fn(LOG_INFO,"rend joined circ %d already here. attaching. (stream %d sec old)",
  734. rendcirc->n_circ_id, conn_age);
  735. link_apconn_to_circ(conn, rendcirc);
  736. if (connection_ap_handshake_send_begin(conn, rendcirc) < 0)
  737. return 0; /* already marked, let them fade away */
  738. return 1;
  739. }
  740. if (rendcirc && rendcirc->purpose == CIRCUIT_PURPOSE_C_REND_READY_INTRO_ACKED) {
  741. log_fn(LOG_INFO,"pending-join circ %d already here, with intro ack. Stalling. (stream %d sec old)", rendcirc->n_circ_id, conn_age);
  742. return 0;
  743. }
  744. /* it's on its way. find an intro circ. */
  745. retval = circuit_get_open_circ_or_launch(conn, CIRCUIT_PURPOSE_C_INTRODUCE_ACK_WAIT, &introcirc);
  746. if (retval < 0) return -1; /* failed */
  747. if (retval > 0) {
  748. /* one has already sent the intro. keep waiting. */
  749. tor_assert(introcirc);
  750. log_fn(LOG_INFO,"Intro circ %d present and awaiting ack (rend %d). Stalling. (stream %d sec old)",
  751. introcirc->n_circ_id, rendcirc ? rendcirc->n_circ_id : 0, conn_age);
  752. return 0;
  753. }
  754. /* now rendcirc and introcirc are each either undefined or not finished */
  755. if (rendcirc && introcirc && rendcirc->purpose == CIRCUIT_PURPOSE_C_REND_READY) {
  756. log_fn(LOG_INFO,"ready rend circ %d already here (no intro-ack yet on intro %d). (stream %d sec old)",
  757. rendcirc->n_circ_id, introcirc->n_circ_id, conn_age);
  758. tor_assert(introcirc->purpose == CIRCUIT_PURPOSE_C_INTRODUCING);
  759. if (introcirc->state == CIRCUIT_STATE_OPEN) {
  760. log_fn(LOG_INFO,"found open intro circ %d (rend %d); sending introduction. (stream %d sec old)",
  761. introcirc->n_circ_id, rendcirc->n_circ_id, conn_age);
  762. /* XXX here we should cannibalize the rend circ if it's a zero service id */
  763. if (rend_client_send_introduction(introcirc, rendcirc) < 0) {
  764. return -1;
  765. }
  766. rendcirc->timestamp_dirty = time(NULL);
  767. introcirc->timestamp_dirty = time(NULL);
  768. assert_circuit_ok(rendcirc);
  769. assert_circuit_ok(introcirc);
  770. return 0;
  771. }
  772. }
  773. log_fn(LOG_INFO,"Intro (%d) and rend (%d) circs are not both ready. Stalling conn. (%d sec old)",
  774. introcirc ? introcirc->n_circ_id : 0,
  775. rendcirc ? rendcirc->n_circ_id : 0, conn_age);
  776. return 0;
  777. }
  778. }