circuituse.c 30 KB

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