circuituse.c 33 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938
  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 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 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. /** Remove any elements in <b>needed_ports</b> that are handled by an
  223. * open or in-progress circuit.
  224. */
  225. void
  226. circuit_remove_handled_ports(smartlist_t *needed_ports) {
  227. int i;
  228. uint16_t *port;
  229. for (i = 0; i < smartlist_len(needed_ports); ++i) {
  230. port = smartlist_get(needed_ports, i);
  231. tor_assert(*port);
  232. if (circuit_stream_is_being_handled(NULL, *port, 2)) {
  233. // log_fn(LOG_DEBUG,"Port %d is already being handled; removing.", port);
  234. smartlist_del(needed_ports, i--);
  235. tor_free(port);
  236. } else {
  237. log_fn(LOG_DEBUG,"Port %d is not handled.", *port);
  238. }
  239. }
  240. }
  241. /** Return 1 if at least <b>min</b> general-purpose circuits will have
  242. * an acceptable exit node for conn if conn is defined, else for "*:port".
  243. * Else return 0.
  244. */
  245. int circuit_stream_is_being_handled(connection_t *conn, uint16_t port, int min) {
  246. circuit_t *circ;
  247. routerinfo_t *exitrouter;
  248. int num=0;
  249. time_t now = time(NULL);
  250. for (circ=global_circuitlist;circ;circ = circ->next) {
  251. if (CIRCUIT_IS_ORIGIN(circ) &&
  252. !circ->marked_for_close &&
  253. circ->purpose == CIRCUIT_PURPOSE_C_GENERAL &&
  254. (!circ->timestamp_dirty ||
  255. circ->timestamp_dirty + get_options()->NewCircuitPeriod < now)) {
  256. exitrouter = router_get_by_digest(circ->build_state->chosen_exit_digest);
  257. if (exitrouter &&
  258. ((conn && connection_ap_can_use_exit(conn, exitrouter)) ||
  259. (!conn &&
  260. router_compare_addr_to_addr_policy(0, port, exitrouter->exit_policy) !=
  261. ADDR_POLICY_REJECTED))) {
  262. if (++num >= min)
  263. return 1;
  264. }
  265. }
  266. }
  267. return 0;
  268. }
  269. /** Build a new test circuit every 5 minutes */
  270. #define TESTING_CIRCUIT_INTERVAL 300
  271. /** This function is called once a second. Its job is to make sure
  272. * all services we offer have enough circuits available. Some
  273. * services just want enough circuits for current tasks, whereas
  274. * others want a minimum set of idle circuits hanging around.
  275. */
  276. void circuit_build_needed_circs(time_t now) {
  277. static long time_to_new_circuit = 0;
  278. circuit_t *circ;
  279. /* launch a new circ for any pending streams that need one */
  280. connection_ap_attach_pending();
  281. /* make sure any hidden services have enough intro points */
  282. if (has_fetched_directory)
  283. rend_services_introduce();
  284. circ = circuit_get_youngest_clean_open(CIRCUIT_PURPOSE_C_GENERAL);
  285. if (time_to_new_circuit < now) {
  286. circuit_reset_failure_count(1);
  287. time_to_new_circuit = now + get_options()->NewCircuitPeriod;
  288. if (proxy_mode(get_options()))
  289. client_dns_clean();
  290. circuit_expire_old_circuits();
  291. if (get_options()->RunTesting &&
  292. circ &&
  293. circ->timestamp_created + TESTING_CIRCUIT_INTERVAL < now) {
  294. log_fn(LOG_INFO,"Creating a new testing circuit.");
  295. circuit_launch_by_identity(CIRCUIT_PURPOSE_C_GENERAL, NULL);
  296. }
  297. }
  298. #if 0
  299. /** How many simultaneous in-progress general-purpose circuits do we
  300. * want to be building at once, if there are no open general-purpose
  301. * circuits?
  302. */
  303. #define CIRCUIT_MIN_BUILDING_GENERAL 5
  304. /* if there's no open circ, and less than 5 are on the way,
  305. * go ahead and try another. */
  306. if (!circ && circuit_count_building(CIRCUIT_PURPOSE_C_GENERAL)
  307. < CIRCUIT_MIN_BUILDING_GENERAL) {
  308. circuit_launch_by_identity(CIRCUIT_PURPOSE_C_GENERAL, NULL);
  309. }
  310. #endif
  311. /* if we know of a port that's been requested recently and no
  312. * circuit is currently available that can handle it, start one
  313. * for that too. */
  314. if (!circuit_all_predicted_ports_handled(now)) {
  315. circuit_launch_by_identity(CIRCUIT_PURPOSE_C_GENERAL, NULL);
  316. }
  317. /* XXX count idle rendezvous circs and build more */
  318. }
  319. /** If the stream <b>conn</b> is a member of any of the linked
  320. * lists of <b>circ</b>, then remove it from the list.
  321. */
  322. void circuit_detach_stream(circuit_t *circ, connection_t *conn) {
  323. connection_t *prevconn;
  324. tor_assert(circ);
  325. tor_assert(conn);
  326. conn->cpath_layer = NULL; /* make sure we don't keep a stale pointer */
  327. if (conn == circ->p_streams) {
  328. circ->p_streams = conn->next_stream;
  329. return;
  330. }
  331. if (conn == circ->n_streams) {
  332. circ->n_streams = conn->next_stream;
  333. return;
  334. }
  335. if (conn == circ->resolving_streams) {
  336. circ->resolving_streams = conn->next_stream;
  337. return;
  338. }
  339. for (prevconn = circ->p_streams;
  340. prevconn && prevconn->next_stream && prevconn->next_stream != conn;
  341. prevconn = prevconn->next_stream)
  342. ;
  343. if (prevconn && prevconn->next_stream) {
  344. prevconn->next_stream = conn->next_stream;
  345. return;
  346. }
  347. for (prevconn = circ->n_streams;
  348. prevconn && prevconn->next_stream && prevconn->next_stream != conn;
  349. prevconn = prevconn->next_stream)
  350. ;
  351. if (prevconn && prevconn->next_stream) {
  352. prevconn->next_stream = conn->next_stream;
  353. return;
  354. }
  355. for (prevconn = circ->resolving_streams;
  356. prevconn && prevconn->next_stream && prevconn->next_stream != conn;
  357. prevconn = prevconn->next_stream)
  358. ;
  359. if (prevconn && prevconn->next_stream) {
  360. prevconn->next_stream = conn->next_stream;
  361. return;
  362. }
  363. log_fn(LOG_ERR,"edge conn not in circuit's list?");
  364. tor_assert(0); /* should never get here */
  365. }
  366. /** Notify the global circuit list that <b>conn</b> is about to be
  367. * removed and then freed.
  368. *
  369. * If it's an OR conn, then mark-for-close all the circuits that use
  370. * that conn.
  371. *
  372. * If it's an edge conn, then detach it from its circ, so we don't
  373. * try to reference it later.
  374. */
  375. void circuit_about_to_close_connection(connection_t *conn) {
  376. /* currently, we assume it's too late to flush conn's buf here.
  377. * down the road, maybe we'll consider that eof doesn't mean can't-write
  378. */
  379. circuit_t *circ;
  380. switch (conn->type) {
  381. case CONN_TYPE_OR:
  382. if (conn->state != OR_CONN_STATE_OPEN) {
  383. /* Inform any pending (not attached) circs that they should give up. */
  384. circuit_n_conn_done(conn, 0);
  385. }
  386. /* Now close all the attached circuits on it. */
  387. while ((circ = circuit_get_by_conn(conn))) {
  388. if (circ->n_conn == conn) /* it's closing in front of us */
  389. circ->n_conn = NULL;
  390. if (circ->p_conn == conn) /* it's closing behind us */
  391. circ->p_conn = NULL;
  392. circuit_mark_for_close(circ);
  393. }
  394. return;
  395. case CONN_TYPE_AP:
  396. case CONN_TYPE_EXIT:
  397. /* It's an edge conn. Need to remove it from the linked list of
  398. * conn's for this circuit. Confirm that 'end' relay command has
  399. * been sent. But don't kill the circuit.
  400. */
  401. circ = circuit_get_by_conn(conn);
  402. if (!circ)
  403. return;
  404. circuit_detach_stream(circ, conn);
  405. } /* end switch */
  406. }
  407. /** Don't keep more than 10 unused open circuits around. */
  408. #define MAX_UNUSED_OPEN_CIRCUITS 10
  409. /** Find each circuit that has been dirty for too long, and has
  410. * no streams on it: mark it for close.
  411. *
  412. * Also, if there are more than MAX_UNUSED_OPEN_CIRCUITS open and
  413. * unused circuits, then mark the excess circs for close.
  414. */
  415. static void
  416. circuit_expire_old_circuits(void)
  417. {
  418. circuit_t *circ;
  419. time_t now = time(NULL);
  420. smartlist_t *unused_open_circs;
  421. int i;
  422. unused_open_circs = smartlist_create();
  423. for (circ = global_circuitlist; circ; circ = circ->next) {
  424. if (circ->marked_for_close)
  425. continue;
  426. /* If the circuit has been dirty for too long, and there are no streams
  427. * on it, mark it for close.
  428. */
  429. if (circ->timestamp_dirty &&
  430. circ->timestamp_dirty + get_options()->NewCircuitPeriod < now &&
  431. !circ->p_conn && /* we're the origin */
  432. !circ->p_streams /* nothing attached */ ) {
  433. log_fn(LOG_DEBUG,"Closing n_circ_id %d (dirty %d secs ago, purp %d)",circ->n_circ_id,
  434. (int)(now - circ->timestamp_dirty), circ->purpose);
  435. /* (only general and purpose_c circs can get dirty) */
  436. tor_assert(!circ->n_streams);
  437. tor_assert(circ->purpose <= CIRCUIT_PURPOSE_C_REND_JOINED);
  438. circuit_mark_for_close(circ);
  439. } else if (!circ->timestamp_dirty && CIRCUIT_IS_ORIGIN(circ) &&
  440. circ->state == CIRCUIT_STATE_OPEN &&
  441. circ->purpose == CIRCUIT_PURPOSE_C_GENERAL) {
  442. #define CIRCUIT_UNUSED_CIRC_TIMEOUT 3600 /* an hour */
  443. if (circ->timestamp_created + CIRCUIT_UNUSED_CIRC_TIMEOUT < now) {
  444. log_fn(LOG_DEBUG,"Closing circuit that has been unused for %d seconds.",
  445. (int)(now - circ->timestamp_created));
  446. circuit_mark_for_close(circ);
  447. } else {
  448. /* Also, gather a list of open unused general circuits that we created.
  449. * Because we add elements to the front of global_circuitlist,
  450. * the last elements of unused_open_circs will be the oldest
  451. * ones.
  452. */
  453. smartlist_add(unused_open_circs, circ);
  454. }
  455. }
  456. }
  457. for (i = MAX_UNUSED_OPEN_CIRCUITS; i < smartlist_len(unused_open_circs); ++i) {
  458. circuit_t *circ = smartlist_get(unused_open_circs, i);
  459. log_fn(LOG_DEBUG,"Expiring excess clean circ (n_circ_id %d, purp %d)",
  460. circ->n_circ_id, circ->purpose);
  461. circuit_mark_for_close(circ);
  462. }
  463. smartlist_free(unused_open_circs);
  464. }
  465. /** The circuit <b>circ</b> has just become open. Take the next
  466. * step: for rendezvous circuits, we pass circ to the appropriate
  467. * function in rendclient or rendservice. For general circuits, we
  468. * call connection_ap_attach_pending, which looks for pending streams
  469. * that could use circ.
  470. */
  471. void circuit_has_opened(circuit_t *circ) {
  472. control_event_circuit_status(circ, CIRC_EVENT_BUILT);
  473. switch (circ->purpose) {
  474. case CIRCUIT_PURPOSE_C_ESTABLISH_REND:
  475. rend_client_rendcirc_has_opened(circ);
  476. break;
  477. case CIRCUIT_PURPOSE_C_INTRODUCING:
  478. rend_client_introcirc_has_opened(circ);
  479. break;
  480. case CIRCUIT_PURPOSE_C_GENERAL:
  481. /* Tell any AP connections that have been waiting for a new
  482. * circuit that one is ready. */
  483. connection_ap_attach_pending();
  484. break;
  485. case CIRCUIT_PURPOSE_S_ESTABLISH_INTRO:
  486. /* at Bob, waiting for introductions */
  487. rend_service_intro_has_opened(circ);
  488. break;
  489. case CIRCUIT_PURPOSE_S_CONNECT_REND:
  490. /* at Bob, connecting to rend point */
  491. rend_service_rendezvous_has_opened(circ);
  492. break;
  493. default:
  494. log_fn(LOG_ERR,"unhandled purpose %d",circ->purpose);
  495. tor_assert(0);
  496. }
  497. }
  498. /*~ Called whenever a circuit could not be successfully built.
  499. */
  500. void circuit_build_failed(circuit_t *circ) {
  501. /* we should examine circ and see if it failed because of
  502. * the last hop or an earlier hop. then use this info below.
  503. */
  504. int failed_at_last_hop = 0;
  505. /* If the last hop isn't open, and the second-to-last is, we failed
  506. * at the last hop. */
  507. if (circ->cpath &&
  508. circ->cpath->prev->state != CPATH_STATE_OPEN &&
  509. circ->cpath->prev->prev->state == CPATH_STATE_OPEN) {
  510. failed_at_last_hop = 1;
  511. }
  512. switch (circ->purpose) {
  513. case CIRCUIT_PURPOSE_C_GENERAL:
  514. if (circ->state != CIRCUIT_STATE_OPEN) {
  515. /* If we never built the circuit, note it as a failure. */
  516. /* Note that we can't just check circ->cpath here, because if
  517. * circuit-building failed immediately, it won't be set yet. */
  518. circuit_increment_failure_count();
  519. }
  520. break;
  521. case CIRCUIT_PURPOSE_S_ESTABLISH_INTRO:
  522. /* at Bob, waiting for introductions */
  523. if (circ->state != CIRCUIT_STATE_OPEN) {
  524. circuit_increment_failure_count();
  525. }
  526. /* no need to care here, because bob will rebuild intro
  527. * points periodically. */
  528. break;
  529. case CIRCUIT_PURPOSE_C_INTRODUCING:
  530. /* at Alice, connecting to intro point */
  531. /* Don't increment failure count, since Bob may have picked
  532. * the introduction point maliciously */
  533. /* Alice will pick a new intro point when this one dies, if
  534. * the stream in question still cares. No need to act here. */
  535. break;
  536. case CIRCUIT_PURPOSE_C_ESTABLISH_REND:
  537. /* at Alice, waiting for Bob */
  538. if (circ->state != CIRCUIT_STATE_OPEN) {
  539. circuit_increment_failure_count();
  540. }
  541. /* Alice will pick a new rend point when this one dies, if
  542. * the stream in question still cares. No need to act here. */
  543. break;
  544. case CIRCUIT_PURPOSE_S_CONNECT_REND:
  545. /* at Bob, connecting to rend point */
  546. /* Don't increment failure count, since Alice may have picked
  547. * the rendezvous point maliciously */
  548. if (failed_at_last_hop) {
  549. log_fn(LOG_INFO,"Couldn't connect to Alice's chosen rend point %s. Sucks to be Alice.", circ->build_state->chosen_exit_name);
  550. } else {
  551. log_fn(LOG_INFO,"Couldn't connect to Alice's chosen rend point %s, because an earlier node failed.",
  552. circ->build_state->chosen_exit_name);
  553. rend_service_relaunch_rendezvous(circ);
  554. }
  555. break;
  556. default:
  557. /* Other cases are impossible, since this function is only called with
  558. * unbuilt circuits. */
  559. tor_assert(0);
  560. }
  561. }
  562. /** Number of consecutive failures so far; should only be touched by
  563. * circuit_launch_new and circuit_*_failure_count.
  564. */
  565. static int n_circuit_failures = 0;
  566. static int did_circs_fail_last_period = 0;
  567. /** Don't retry launching a new circuit if we try this many times with no
  568. * success. */
  569. #define MAX_CIRCUIT_FAILURES 5
  570. circuit_t *circuit_launch_by_identity(uint8_t purpose, const char *exit_digest)
  571. {
  572. if (!has_fetched_directory) {
  573. log_fn(LOG_DEBUG,"Haven't fetched directory yet; canceling circuit launch.");
  574. return NULL;
  575. }
  576. if (did_circs_fail_last_period &&
  577. n_circuit_failures > MAX_CIRCUIT_FAILURES) {
  578. /* too many failed circs in a row. don't try. */
  579. // log_fn(LOG_INFO,"%d failures so far, not trying.",n_circuit_failures);
  580. return NULL;
  581. }
  582. /* try a circ. if it fails, circuit_mark_for_close will increment n_circuit_failures */
  583. return circuit_establish_circuit(purpose, exit_digest);
  584. }
  585. /** Launch a new circuit and return a pointer to it. Return NULL if you failed. */
  586. circuit_t *circuit_launch_by_nickname(uint8_t purpose, const char *exit_nickname)
  587. {
  588. const char *digest = NULL;
  589. if (exit_nickname) {
  590. routerinfo_t *r = router_get_by_nickname(exit_nickname);
  591. if (!r) {
  592. log_fn(LOG_WARN, "No such OR as '%s'", exit_nickname);
  593. return NULL;
  594. }
  595. digest = r->identity_digest;
  596. }
  597. return circuit_launch_by_identity(purpose, digest);
  598. }
  599. /** Record another failure at opening a general circuit. When we have
  600. * too many, we'll stop trying for the remainder of this minute.
  601. */
  602. static void circuit_increment_failure_count(void) {
  603. ++n_circuit_failures;
  604. log_fn(LOG_DEBUG,"n_circuit_failures now %d.",n_circuit_failures);
  605. }
  606. /** Reset the failure count for opening general circuits. This means
  607. * we will try MAX_CIRCUIT_FAILURES times more (if necessary) before
  608. * stopping again.
  609. */
  610. void circuit_reset_failure_count(int timeout) {
  611. if (timeout && n_circuit_failures > MAX_CIRCUIT_FAILURES)
  612. did_circs_fail_last_period = 1;
  613. else
  614. did_circs_fail_last_period = 0;
  615. n_circuit_failures = 0;
  616. }
  617. /** Find an open circ that we're happy with: return 1. If there isn't
  618. * one, and there isn't one on the way, launch one and return 0. If it
  619. * will never work, return -1.
  620. *
  621. * Write the found or in-progress or launched circ into *circp.
  622. */
  623. static int
  624. circuit_get_open_circ_or_launch(connection_t *conn,
  625. uint8_t desired_circuit_purpose,
  626. circuit_t **circp) {
  627. circuit_t *circ;
  628. uint32_t addr;
  629. int is_resolve;
  630. tor_assert(conn);
  631. tor_assert(circp);
  632. tor_assert(conn->state == AP_CONN_STATE_CIRCUIT_WAIT);
  633. is_resolve = conn->socks_request->command == SOCKS_COMMAND_RESOLVE;
  634. circ = circuit_get_best(conn, 1, desired_circuit_purpose);
  635. if (circ) {
  636. *circp = circ;
  637. return 1; /* we're happy */
  638. }
  639. /* Do we need to check exit policy? */
  640. if (!is_resolve && !connection_edge_is_rendezvous_stream(conn)) {
  641. addr = client_dns_lookup_entry(conn->socks_request->address);
  642. if (router_exit_policy_all_routers_reject(addr, conn->socks_request->port)) {
  643. log_fn(LOG_NOTICE,"No Tor server exists that allows exit to %s:%d. Rejecting.",
  644. conn->socks_request->address, conn->socks_request->port);
  645. return -1;
  646. }
  647. }
  648. /* is one already on the way? */
  649. circ = circuit_get_best(conn, 0, desired_circuit_purpose);
  650. if (!circ) {
  651. char *exitname=NULL;
  652. uint8_t new_circ_purpose;
  653. if (desired_circuit_purpose == CIRCUIT_PURPOSE_C_INTRODUCE_ACK_WAIT) {
  654. /* need to pick an intro point */
  655. exitname = rend_client_get_random_intro(conn->rend_query);
  656. if (!exitname) {
  657. log_fn(LOG_WARN,"Couldn't get an intro point for '%s'. Closing.",
  658. conn->rend_query);
  659. return -1;
  660. }
  661. if (!router_get_by_nickname(exitname)) {
  662. log_fn(LOG_WARN,"Advertised intro point '%s' is not known. Closing.", exitname);
  663. tor_free(exitname);
  664. return -1;
  665. }
  666. /* XXX if we failed, then refetch the descriptor */
  667. log_fn(LOG_INFO,"Chose %s as intro point for %s.", exitname, conn->rend_query);
  668. }
  669. /* If we have specified a particular exit node for our
  670. * connection, then be sure to open a circuit to that exit node.
  671. */
  672. if (desired_circuit_purpose == CIRCUIT_PURPOSE_C_GENERAL) {
  673. if (conn->chosen_exit_name) {
  674. exitname = tor_strdup(conn->chosen_exit_name);
  675. if (!router_get_by_nickname(exitname)) {
  676. log_fn(LOG_WARN,"Requested exit point '%s' is not known. Closing.", exitname);
  677. tor_free(exitname);
  678. return -1;
  679. }
  680. }
  681. }
  682. if (desired_circuit_purpose == CIRCUIT_PURPOSE_C_REND_JOINED)
  683. new_circ_purpose = CIRCUIT_PURPOSE_C_ESTABLISH_REND;
  684. else if (desired_circuit_purpose == CIRCUIT_PURPOSE_C_INTRODUCE_ACK_WAIT)
  685. new_circ_purpose = CIRCUIT_PURPOSE_C_INTRODUCING;
  686. else
  687. new_circ_purpose = desired_circuit_purpose;
  688. circ = circuit_launch_by_nickname(new_circ_purpose, exitname);
  689. tor_free(exitname);
  690. if (circ &&
  691. desired_circuit_purpose != CIRCUIT_PURPOSE_C_GENERAL) {
  692. /* then write the service_id into circ */
  693. strlcpy(circ->rend_query, conn->rend_query, sizeof(circ->rend_query));
  694. }
  695. }
  696. if (!circ)
  697. log_fn(LOG_INFO,"No safe circuit (purpose %d) ready for edge connection; delaying.",
  698. desired_circuit_purpose);
  699. *circp = circ;
  700. return 0;
  701. }
  702. /** Attach the AP stream <b>apconn</b> to circ's linked list of
  703. * p_streams. Also set apconn's cpath_layer to the last hop in
  704. * circ's cpath.
  705. */
  706. static void link_apconn_to_circ(connection_t *apconn, circuit_t *circ) {
  707. /* add it into the linked list of streams on this circuit */
  708. log_fn(LOG_DEBUG,"attaching new conn to circ. n_circ_id %d.", circ->n_circ_id);
  709. apconn->timestamp_lastread = time(NULL); /* reset it, so we can measure circ timeouts */
  710. apconn->next_stream = circ->p_streams;
  711. /* assert_connection_ok(conn, time(NULL)); */
  712. circ->p_streams = apconn;
  713. tor_assert(CIRCUIT_IS_ORIGIN(circ));
  714. tor_assert(circ->cpath);
  715. tor_assert(circ->cpath->prev);
  716. tor_assert(circ->cpath->prev->state == CPATH_STATE_OPEN);
  717. apconn->cpath_layer = circ->cpath->prev;
  718. }
  719. /** Try to find a safe live circuit for CONN_TYPE_AP connection conn. If
  720. * we don't find one: if conn cannot be handled by any known nodes,
  721. * warn and return -1 (conn needs to die);
  722. * else launch new circuit (if necessary) and return 0.
  723. * Otherwise, associate conn with a safe live circuit, do the
  724. * right next step, and return 1.
  725. */
  726. int connection_ap_handshake_attach_circuit(connection_t *conn) {
  727. int retval;
  728. int conn_age;
  729. tor_assert(conn);
  730. tor_assert(conn->type == CONN_TYPE_AP);
  731. tor_assert(conn->state == AP_CONN_STATE_CIRCUIT_WAIT);
  732. tor_assert(conn->socks_request);
  733. conn_age = time(NULL) - conn->timestamp_created;
  734. if (conn_age > CONN_AP_MAX_ATTACH_DELAY) {
  735. log_fn(LOG_NOTICE,"Giving up on unattached conn (%d sec old).", conn_age);
  736. return -1;
  737. }
  738. if (!connection_edge_is_rendezvous_stream(conn)) { /* we're a general conn */
  739. circuit_t *circ=NULL;
  740. if (conn->chosen_exit_name) {
  741. routerinfo_t *router = router_get_by_nickname(conn->chosen_exit_name);
  742. if (!router) {
  743. log_fn(LOG_WARN,"Requested exit point '%s' is not known. Closing.",
  744. conn->chosen_exit_name);
  745. return -1;
  746. }
  747. if (!connection_ap_can_use_exit(conn, router)) {
  748. log_fn(LOG_WARN, "Requested exit point '%s' would refuse request. Closing.",
  749. conn->chosen_exit_name);
  750. return -1;
  751. }
  752. }
  753. /* find the circuit that we should use, if there is one. */
  754. retval = circuit_get_open_circ_or_launch(conn, CIRCUIT_PURPOSE_C_GENERAL, &circ);
  755. if (retval < 1)
  756. return retval;
  757. /* We have found a suitable circuit for our conn. Hurray. */
  758. tor_assert(circ);
  759. log_fn(LOG_DEBUG,"Attaching apconn to general circ %d (stream %d sec old).",
  760. circ->n_circ_id, conn_age);
  761. /* here, print the circ's path. so people can figure out which circs are sucking. */
  762. circuit_log_path(LOG_INFO,circ);
  763. if (!circ->timestamp_dirty)
  764. circ->timestamp_dirty = time(NULL);
  765. link_apconn_to_circ(conn, circ);
  766. tor_assert(conn->socks_request);
  767. if (conn->socks_request->command == SOCKS_COMMAND_CONNECT)
  768. connection_ap_handshake_send_begin(conn, circ);
  769. else
  770. connection_ap_handshake_send_resolve(conn, circ);
  771. return 1;
  772. } else { /* we're a rendezvous conn */
  773. circuit_t *rendcirc=NULL, *introcirc=NULL;
  774. tor_assert(!conn->cpath_layer);
  775. /* start by finding a rendezvous circuit for us */
  776. retval = circuit_get_open_circ_or_launch(conn, CIRCUIT_PURPOSE_C_REND_JOINED, &rendcirc);
  777. if (retval < 0) return -1; /* failed */
  778. if (retval > 0) {
  779. tor_assert(rendcirc);
  780. /* one is already established, attach */
  781. log_fn(LOG_INFO,"rend joined circ %d already here. attaching. (stream %d sec old)",
  782. rendcirc->n_circ_id, conn_age);
  783. link_apconn_to_circ(conn, rendcirc);
  784. if (connection_ap_handshake_send_begin(conn, rendcirc) < 0)
  785. return 0; /* already marked, let them fade away */
  786. return 1;
  787. }
  788. if (rendcirc && rendcirc->purpose == CIRCUIT_PURPOSE_C_REND_READY_INTRO_ACKED) {
  789. log_fn(LOG_INFO,"pending-join circ %d already here, with intro ack. Stalling. (stream %d sec old)", rendcirc->n_circ_id, conn_age);
  790. return 0;
  791. }
  792. /* it's on its way. find an intro circ. */
  793. retval = circuit_get_open_circ_or_launch(conn, CIRCUIT_PURPOSE_C_INTRODUCE_ACK_WAIT, &introcirc);
  794. if (retval < 0) return -1; /* failed */
  795. if (retval > 0) {
  796. /* one has already sent the intro. keep waiting. */
  797. tor_assert(introcirc);
  798. log_fn(LOG_INFO,"Intro circ %d present and awaiting ack (rend %d). Stalling. (stream %d sec old)",
  799. introcirc->n_circ_id, rendcirc ? rendcirc->n_circ_id : 0, conn_age);
  800. return 0;
  801. }
  802. /* now rendcirc and introcirc are each either undefined or not finished */
  803. if (rendcirc && introcirc && rendcirc->purpose == CIRCUIT_PURPOSE_C_REND_READY) {
  804. log_fn(LOG_INFO,"ready rend circ %d already here (no intro-ack yet on intro %d). (stream %d sec old)",
  805. rendcirc->n_circ_id, introcirc->n_circ_id, conn_age);
  806. tor_assert(introcirc->purpose == CIRCUIT_PURPOSE_C_INTRODUCING);
  807. if (introcirc->state == CIRCUIT_STATE_OPEN) {
  808. log_fn(LOG_INFO,"found open intro circ %d (rend %d); sending introduction. (stream %d sec old)",
  809. introcirc->n_circ_id, rendcirc->n_circ_id, conn_age);
  810. /* XXX here we should cannibalize the rend circ if it's a zero service id */
  811. if (rend_client_send_introduction(introcirc, rendcirc) < 0) {
  812. return -1;
  813. }
  814. rendcirc->timestamp_dirty = time(NULL);
  815. introcirc->timestamp_dirty = time(NULL);
  816. assert_circuit_ok(rendcirc);
  817. assert_circuit_ok(introcirc);
  818. return 0;
  819. }
  820. }
  821. log_fn(LOG_INFO,"Intro (%d) and rend (%d) circs are not both ready. Stalling conn. (%d sec old)",
  822. introcirc ? introcirc->n_circ_id : 0,
  823. rendcirc ? rendcirc->n_circ_id : 0, conn_age);
  824. return 0;
  825. }
  826. }