circuituse.c 37 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038
  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. tor_assert(circ);
  31. tor_assert(conn);
  32. tor_assert(conn->socks_request);
  33. if (!CIRCUIT_IS_ORIGIN(circ))
  34. return 0; /* this circ doesn't start at us */
  35. if (must_be_open && (circ->state != CIRCUIT_STATE_OPEN || !circ->n_conn))
  36. return 0; /* ignore non-open circs */
  37. if (circ->marked_for_close)
  38. return 0;
  39. /* if this circ isn't our purpose, skip. */
  40. if (purpose == CIRCUIT_PURPOSE_C_REND_JOINED && !must_be_open) {
  41. if (circ->purpose != CIRCUIT_PURPOSE_C_ESTABLISH_REND &&
  42. circ->purpose != CIRCUIT_PURPOSE_C_REND_READY &&
  43. circ->purpose != CIRCUIT_PURPOSE_C_REND_READY_INTRO_ACKED &&
  44. circ->purpose != CIRCUIT_PURPOSE_C_REND_JOINED)
  45. return 0;
  46. } else if (purpose == CIRCUIT_PURPOSE_C_INTRODUCE_ACK_WAIT && !must_be_open) {
  47. if (circ->purpose != CIRCUIT_PURPOSE_C_INTRODUCING &&
  48. circ->purpose != CIRCUIT_PURPOSE_C_INTRODUCE_ACK_WAIT)
  49. return 0;
  50. } else {
  51. if (purpose != circ->purpose)
  52. return 0;
  53. }
  54. if (purpose == CIRCUIT_PURPOSE_C_GENERAL)
  55. if (circ->timestamp_dirty &&
  56. circ->timestamp_dirty+get_options()->MaxCircuitDirtiness <= now)
  57. return 0;
  58. /* decide if this circ is suitable for this conn */
  59. /* for rend circs, circ->cpath->prev is not the last router in the
  60. * circuit, it's the magical extra bob hop. so just check the nickname
  61. * of the one we meant to finish at.
  62. */
  63. exitrouter = router_get_by_digest(circ->build_state->chosen_exit_digest);
  64. if (!exitrouter) {
  65. log_fn(LOG_INFO,"Skipping broken circ (exit router vanished)");
  66. return 0; /* this circuit is screwed and doesn't know it yet */
  67. }
  68. if (!circ->build_state->need_uptime &&
  69. smartlist_string_num_isin(get_options()->LongLivedPorts,
  70. conn->socks_request->port))
  71. return 0;
  72. if (conn->socks_request->command == SOCKS_COMMAND_CONNECT) {
  73. if (purpose == CIRCUIT_PURPOSE_C_GENERAL) {
  74. if (!connection_ap_can_use_exit(conn, exitrouter)) {
  75. /* can't exit from this router */
  76. return 0;
  77. }
  78. } else { /* not general */
  79. if (rend_cmp_service_ids(conn->rend_query, circ->rend_query)) {
  80. /* this circ is not for this conn */
  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. b->build_state->is_internal ||
  104. a->timestamp_created > b->timestamp_created)
  105. return 1;
  106. }
  107. break;
  108. case CIRCUIT_PURPOSE_C_INTRODUCE_ACK_WAIT:
  109. /* the closer it is to ack_wait the better it is */
  110. if (a->purpose > b->purpose)
  111. return 1;
  112. break;
  113. case CIRCUIT_PURPOSE_C_REND_JOINED:
  114. /* the closer it is to rend_joined the better it is */
  115. if (a->purpose > b->purpose)
  116. return 1;
  117. break;
  118. }
  119. return 0;
  120. }
  121. /** Find the best circ that conn can use, preferably one which is
  122. * dirty. Circ must not be too old.
  123. *
  124. * Conn must be defined.
  125. *
  126. * If must_be_open, ignore circs not in CIRCUIT_STATE_OPEN.
  127. *
  128. * circ_purpose specifies what sort of circuit we must have.
  129. * It can be C_GENERAL, C_INTRODUCE_ACK_WAIT, or C_REND_JOINED.
  130. *
  131. * If it's REND_JOINED and must_be_open==0, then return the closest
  132. * rendezvous-purposed circuit that you can find.
  133. *
  134. * If it's INTRODUCE_ACK_WAIT and must_be_open==0, then return the
  135. * closest introduce-purposed circuit that you can find.
  136. */
  137. static circuit_t *
  138. circuit_get_best(connection_t *conn, int must_be_open, uint8_t purpose)
  139. {
  140. circuit_t *circ, *best=NULL;
  141. time_t now = time(NULL);
  142. tor_assert(conn);
  143. tor_assert(purpose == CIRCUIT_PURPOSE_C_GENERAL ||
  144. purpose == CIRCUIT_PURPOSE_C_INTRODUCE_ACK_WAIT ||
  145. purpose == CIRCUIT_PURPOSE_C_REND_JOINED);
  146. for (circ=global_circuitlist;circ;circ = circ->next) {
  147. if (!circuit_is_acceptable(circ,conn,must_be_open,purpose,now))
  148. continue;
  149. /* now this is an acceptable circ to hand back. but that doesn't
  150. * mean it's the *best* circ to hand back. try to decide.
  151. */
  152. if (!best || circuit_is_better(circ,best,purpose))
  153. best = circ;
  154. }
  155. return best;
  156. }
  157. /** If we find a circuit that isn't open yet and was born this many
  158. * seconds ago, then assume something went wrong, and cull it.
  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. #if 0
  176. /* some debug logs, to help track bugs */
  177. if (victim->purpose >= CIRCUIT_PURPOSE_C_INTRODUCING &&
  178. victim->purpose <= CIRCUIT_PURPOSE_C_REND_READY_INTRO_ACKED) {
  179. if (!victim->timestamp_dirty)
  180. log_fn(LOG_DEBUG,"Considering %sopen purp %d to %s (circid %d). (clean).",
  181. victim->state == CIRCUIT_STATE_OPEN ? "" : "non",
  182. victim->purpose, victim->build_state->chosen_exit_name,
  183. victim->n_circ_id);
  184. else
  185. log_fn(LOG_DEBUG,"Considering %sopen purp %d to %s (circid %d). %d secs since dirty.",
  186. victim->state == CIRCUIT_STATE_OPEN ? "" : "non",
  187. victim->purpose, victim->build_state->chosen_exit_name,
  188. victim->n_circ_id,
  189. (int)(now - victim->timestamp_dirty));
  190. }
  191. #endif
  192. /* if circ is !open, or if it's open but purpose is a non-finished
  193. * intro or rend, then mark it for close */
  194. if (victim->state != CIRCUIT_STATE_OPEN ||
  195. victim->purpose == CIRCUIT_PURPOSE_C_ESTABLISH_REND ||
  196. victim->purpose == CIRCUIT_PURPOSE_C_INTRODUCING ||
  197. victim->purpose == CIRCUIT_PURPOSE_S_ESTABLISH_INTRO ||
  198. /* it's a rend_ready circ, but it's already picked a query */
  199. (victim->purpose == CIRCUIT_PURPOSE_C_REND_READY &&
  200. victim->rend_query[0]) ||
  201. /* c_rend_ready circs measure age since timestamp_dirty,
  202. * because that's set when they switch purposes
  203. */
  204. /* rend and intro circs become dirty each time they
  205. * make an introduction attempt. so timestamp_dirty
  206. * will reflect the time since the last attempt.
  207. */
  208. ((victim->purpose == CIRCUIT_PURPOSE_C_REND_READY ||
  209. victim->purpose == CIRCUIT_PURPOSE_C_REND_READY_INTRO_ACKED ||
  210. victim->purpose == CIRCUIT_PURPOSE_C_INTRODUCE_ACK_WAIT) &&
  211. victim->timestamp_dirty + MIN_SECONDS_BEFORE_EXPIRING_CIRC > now)) {
  212. if (victim->n_conn)
  213. log_fn(LOG_INFO,"Abandoning circ %s:%d:%d (state %d:%s, purpose %d)",
  214. victim->n_conn->address, victim->n_port, victim->n_circ_id,
  215. victim->state, circuit_state_to_string[victim->state], victim->purpose);
  216. else
  217. log_fn(LOG_INFO,"Abandoning circ %d (state %d:%s, purpose %d)", victim->n_circ_id,
  218. victim->state, circuit_state_to_string[victim->state], victim->purpose);
  219. circuit_log_path(LOG_INFO,victim);
  220. circuit_mark_for_close(victim);
  221. }
  222. }
  223. }
  224. /** Remove any elements in <b>needed_ports</b> that are handled by an
  225. * open or in-progress circuit.
  226. */
  227. void
  228. circuit_remove_handled_ports(smartlist_t *needed_ports) {
  229. int i;
  230. uint16_t *port;
  231. for (i = 0; i < smartlist_len(needed_ports); ++i) {
  232. port = smartlist_get(needed_ports, i);
  233. tor_assert(*port);
  234. if (circuit_stream_is_being_handled(NULL, *port, 2)) {
  235. // log_fn(LOG_DEBUG,"Port %d is already being handled; removing.", port);
  236. smartlist_del(needed_ports, i--);
  237. tor_free(port);
  238. } else {
  239. log_fn(LOG_DEBUG,"Port %d is not handled.", *port);
  240. }
  241. }
  242. }
  243. /** Return 1 if at least <b>min</b> general-purpose circuits will have
  244. * an acceptable exit node for conn if conn is defined, else for "*:port".
  245. * Else return 0.
  246. */
  247. int circuit_stream_is_being_handled(connection_t *conn, uint16_t port, int min) {
  248. circuit_t *circ;
  249. routerinfo_t *exitrouter;
  250. int num=0;
  251. time_t now = time(NULL);
  252. int need_uptime = smartlist_string_num_isin(get_options()->LongLivedPorts,
  253. conn ? conn->socks_request->port : port);
  254. for (circ=global_circuitlist;circ;circ = circ->next) {
  255. if (CIRCUIT_IS_ORIGIN(circ) &&
  256. !circ->marked_for_close &&
  257. circ->purpose == CIRCUIT_PURPOSE_C_GENERAL &&
  258. (!circ->timestamp_dirty ||
  259. circ->timestamp_dirty + get_options()->MaxCircuitDirtiness < now)) {
  260. exitrouter = router_get_by_digest(circ->build_state->chosen_exit_digest);
  261. if (exitrouter &&
  262. (!need_uptime || circ->build_state->need_uptime) &&
  263. ((conn && connection_ap_can_use_exit(conn, exitrouter)) ||
  264. (!conn &&
  265. router_compare_addr_to_addr_policy(0, port, exitrouter->exit_policy) !=
  266. ADDR_POLICY_REJECTED))) {
  267. if (++num >= min)
  268. return 1;
  269. }
  270. }
  271. }
  272. return 0;
  273. }
  274. /** Don't keep more than 10 unused open circuits around. */
  275. #define MAX_UNUSED_OPEN_CIRCUITS 10
  276. /** Figure out how many circuits we have open that are clean. Make
  277. * sure it's enough for all the upcoming behaviors we predict we'll have.
  278. * But if we have too many, close the not-so-useful ones.
  279. */
  280. static void
  281. circuit_predict_and_launch_new(void)
  282. {
  283. circuit_t *circ;
  284. int num=0, num_internal=0, num_uptime_internal=0;
  285. int hidserv_needs_uptime=0, hidserv_needs_capacity=1;
  286. int port_needs_uptime=0, port_needs_capacity=1;
  287. int need_ports, need_hidserv;
  288. time_t now = time(NULL);
  289. /* check if we know of a port that's been requested recently
  290. * and no circuit is currently available that can handle it. */
  291. need_ports = !circuit_all_predicted_ports_handled(now, &port_needs_uptime,
  292. &port_needs_capacity);
  293. need_hidserv = rep_hist_get_predicted_hidserv(now, &hidserv_needs_uptime,
  294. &hidserv_needs_capacity);
  295. for (circ=global_circuitlist;circ;circ = circ->next) {
  296. if (!CIRCUIT_IS_ORIGIN(circ))
  297. continue;
  298. if (circ->marked_for_close)
  299. continue; /* don't mess with marked circs */
  300. if (circ->timestamp_dirty)
  301. continue; /* only count clean circs */
  302. if (circ->purpose != CIRCUIT_PURPOSE_C_GENERAL)
  303. continue; /* only pay attention to general-purpose circs */
  304. num++;
  305. if (circ->build_state->is_internal)
  306. num_internal++;
  307. if (circ->build_state->need_uptime && circ->build_state->is_internal)
  308. num_uptime_internal++;
  309. }
  310. if (num < MAX_UNUSED_OPEN_CIRCUITS) {
  311. /* perhaps we want another */
  312. if (need_ports) {
  313. log_fn(LOG_INFO,"Have %d clean circs (%d internal), need another exit circ.",
  314. num, num_internal);
  315. circuit_launch_by_identity(CIRCUIT_PURPOSE_C_GENERAL, NULL,
  316. port_needs_uptime, port_needs_capacity, 0);
  317. } else if (need_hidserv &&
  318. ((num_uptime_internal<2 && hidserv_needs_uptime) ||
  319. num_internal<2)) {
  320. log_fn(LOG_INFO,"Have %d clean circs (%d uptime-internal, %d internal),"
  321. " need another hidserv circ.", num, num_uptime_internal, num_internal);
  322. circuit_launch_by_identity(CIRCUIT_PURPOSE_C_GENERAL, NULL,
  323. hidserv_needs_uptime, hidserv_needs_capacity, 1);
  324. }
  325. }
  326. }
  327. /** Build a new test circuit every 5 minutes */
  328. #define TESTING_CIRCUIT_INTERVAL 300
  329. /** This function is called once a second. Its job is to make sure
  330. * all services we offer have enough circuits available. Some
  331. * services just want enough circuits for current tasks, whereas
  332. * others want a minimum set of idle circuits hanging around.
  333. */
  334. void circuit_build_needed_circs(time_t now) {
  335. static long time_to_new_circuit = 0;
  336. /* launch a new circ for any pending streams that need one */
  337. connection_ap_attach_pending();
  338. /* make sure any hidden services have enough intro points */
  339. if (has_fetched_directory)
  340. rend_services_introduce();
  341. if (time_to_new_circuit < now) {
  342. circuit_reset_failure_count(1);
  343. time_to_new_circuit = now + get_options()->NewCircuitPeriod;
  344. if (proxy_mode(get_options()))
  345. client_dns_clean();
  346. circuit_expire_old_circuits();
  347. #if 0 /* disable for now, until predict-and-launch-new can cull leftovers */
  348. circ = circuit_get_youngest_clean_open(CIRCUIT_PURPOSE_C_GENERAL);
  349. if (get_options()->RunTesting &&
  350. circ &&
  351. circ->timestamp_created + TESTING_CIRCUIT_INTERVAL < now) {
  352. log_fn(LOG_INFO,"Creating a new testing circuit.");
  353. circuit_launch_by_identity(CIRCUIT_PURPOSE_C_GENERAL, NULL, 0, 0, 0);
  354. }
  355. #endif
  356. }
  357. circuit_predict_and_launch_new();
  358. }
  359. /** If the stream <b>conn</b> is a member of any of the linked
  360. * lists of <b>circ</b>, then remove it from the list.
  361. */
  362. void circuit_detach_stream(circuit_t *circ, connection_t *conn) {
  363. connection_t *prevconn;
  364. tor_assert(circ);
  365. tor_assert(conn);
  366. conn->cpath_layer = NULL; /* make sure we don't keep a stale pointer */
  367. if (conn == circ->p_streams) {
  368. circ->p_streams = conn->next_stream;
  369. return;
  370. }
  371. if (conn == circ->n_streams) {
  372. circ->n_streams = conn->next_stream;
  373. return;
  374. }
  375. if (conn == circ->resolving_streams) {
  376. circ->resolving_streams = conn->next_stream;
  377. return;
  378. }
  379. for (prevconn = circ->p_streams;
  380. prevconn && prevconn->next_stream && prevconn->next_stream != conn;
  381. prevconn = prevconn->next_stream)
  382. ;
  383. if (prevconn && prevconn->next_stream) {
  384. prevconn->next_stream = conn->next_stream;
  385. return;
  386. }
  387. for (prevconn = circ->n_streams;
  388. prevconn && prevconn->next_stream && prevconn->next_stream != conn;
  389. prevconn = prevconn->next_stream)
  390. ;
  391. if (prevconn && prevconn->next_stream) {
  392. prevconn->next_stream = conn->next_stream;
  393. return;
  394. }
  395. for (prevconn = circ->resolving_streams;
  396. prevconn && prevconn->next_stream && prevconn->next_stream != conn;
  397. prevconn = prevconn->next_stream)
  398. ;
  399. if (prevconn && prevconn->next_stream) {
  400. prevconn->next_stream = conn->next_stream;
  401. return;
  402. }
  403. log_fn(LOG_ERR,"edge conn not in circuit's list?");
  404. tor_assert(0); /* should never get here */
  405. }
  406. /** Notify the global circuit list that <b>conn</b> is about to be
  407. * removed and then freed.
  408. *
  409. * If it's an OR conn, then mark-for-close all the circuits that use
  410. * that conn.
  411. *
  412. * If it's an edge conn, then detach it from its circ, so we don't
  413. * try to reference it later.
  414. */
  415. void circuit_about_to_close_connection(connection_t *conn) {
  416. /* currently, we assume it's too late to flush conn's buf here.
  417. * down the road, maybe we'll consider that eof doesn't mean can't-write
  418. */
  419. circuit_t *circ;
  420. switch (conn->type) {
  421. case CONN_TYPE_OR:
  422. if (conn->state != OR_CONN_STATE_OPEN) {
  423. /* Inform any pending (not attached) circs that they should give up. */
  424. circuit_n_conn_done(conn, 0);
  425. }
  426. /* Now close all the attached circuits on it. */
  427. while ((circ = circuit_get_by_conn(conn))) {
  428. if (circ->n_conn == conn) /* it's closing in front of us */
  429. circ->n_conn = NULL;
  430. if (circ->p_conn == conn) /* it's closing behind us */
  431. circ->p_conn = NULL;
  432. circuit_mark_for_close(circ);
  433. }
  434. return;
  435. case CONN_TYPE_AP:
  436. case CONN_TYPE_EXIT:
  437. /* It's an edge conn. Need to remove it from the linked list of
  438. * conn's for this circuit. Confirm that 'end' relay command has
  439. * been sent. But don't kill the circuit.
  440. */
  441. circ = circuit_get_by_conn(conn);
  442. if (!circ)
  443. return;
  444. circuit_detach_stream(circ, conn);
  445. } /* end switch */
  446. }
  447. /** Find each circuit that has been dirty for too long, and has
  448. * no streams on it: mark it for close.
  449. */
  450. static void
  451. circuit_expire_old_circuits(void)
  452. {
  453. circuit_t *circ;
  454. time_t now = time(NULL);
  455. for (circ = global_circuitlist; circ; circ = circ->next) {
  456. if (circ->marked_for_close)
  457. continue;
  458. /* If the circuit has been dirty for too long, and there are no streams
  459. * on it, mark it for close.
  460. */
  461. if (circ->timestamp_dirty &&
  462. circ->timestamp_dirty + get_options()->MaxCircuitDirtiness < now &&
  463. CIRCUIT_IS_ORIGIN(circ) &&
  464. !circ->p_streams /* nothing attached */ ) {
  465. log_fn(LOG_DEBUG,"Closing n_circ_id %d (dirty %d secs ago, purp %d)",circ->n_circ_id,
  466. (int)(now - circ->timestamp_dirty), circ->purpose);
  467. /* (only general and purpose_c circs can get dirty) */
  468. tor_assert(!circ->n_streams);
  469. tor_assert(circ->purpose <= CIRCUIT_PURPOSE_C_REND_JOINED);
  470. circuit_mark_for_close(circ);
  471. } else if (!circ->timestamp_dirty && CIRCUIT_IS_ORIGIN(circ) &&
  472. circ->state == CIRCUIT_STATE_OPEN &&
  473. circ->purpose == CIRCUIT_PURPOSE_C_GENERAL) {
  474. #define CIRCUIT_UNUSED_CIRC_TIMEOUT 3600 /* an hour */
  475. if (circ->timestamp_created + CIRCUIT_UNUSED_CIRC_TIMEOUT < now) {
  476. log_fn(LOG_DEBUG,"Closing circuit that has been unused for %d seconds.",
  477. (int)(now - circ->timestamp_created));
  478. circuit_mark_for_close(circ);
  479. }
  480. }
  481. }
  482. }
  483. /** The circuit <b>circ</b> has just become open. Take the next
  484. * step: for rendezvous circuits, we pass circ to the appropriate
  485. * function in rendclient or rendservice. For general circuits, we
  486. * call connection_ap_attach_pending, which looks for pending streams
  487. * that could use circ.
  488. */
  489. void circuit_has_opened(circuit_t *circ) {
  490. control_event_circuit_status(circ, CIRC_EVENT_BUILT);
  491. switch (circ->purpose) {
  492. case CIRCUIT_PURPOSE_C_ESTABLISH_REND:
  493. rend_client_rendcirc_has_opened(circ);
  494. connection_ap_attach_pending();
  495. break;
  496. case CIRCUIT_PURPOSE_C_INTRODUCING:
  497. rend_client_introcirc_has_opened(circ);
  498. break;
  499. case CIRCUIT_PURPOSE_C_GENERAL:
  500. /* Tell any AP connections that have been waiting for a new
  501. * circuit that one is ready. */
  502. connection_ap_attach_pending();
  503. break;
  504. case CIRCUIT_PURPOSE_S_ESTABLISH_INTRO:
  505. /* at Bob, waiting for introductions */
  506. rend_service_intro_has_opened(circ);
  507. break;
  508. case CIRCUIT_PURPOSE_S_CONNECT_REND:
  509. /* at Bob, connecting to rend point */
  510. rend_service_rendezvous_has_opened(circ);
  511. break;
  512. default:
  513. log_fn(LOG_ERR,"unhandled purpose %d",circ->purpose);
  514. tor_assert(0);
  515. }
  516. }
  517. /*~ Called whenever a circuit could not be successfully built.
  518. */
  519. void circuit_build_failed(circuit_t *circ) {
  520. /* we should examine circ and see if it failed because of
  521. * the last hop or an earlier hop. then use this info below.
  522. */
  523. int failed_at_last_hop = 0;
  524. /* If the last hop isn't open, and the second-to-last is, we failed
  525. * at the last hop. */
  526. if (circ->cpath &&
  527. circ->cpath->prev->state != CPATH_STATE_OPEN &&
  528. circ->cpath->prev->prev->state == CPATH_STATE_OPEN) {
  529. failed_at_last_hop = 1;
  530. }
  531. switch (circ->purpose) {
  532. case CIRCUIT_PURPOSE_C_GENERAL:
  533. if (circ->state != CIRCUIT_STATE_OPEN) {
  534. /* If we never built the circuit, note it as a failure. */
  535. /* Note that we can't just check circ->cpath here, because if
  536. * circuit-building failed immediately, it won't be set yet. */
  537. circuit_increment_failure_count();
  538. }
  539. break;
  540. case CIRCUIT_PURPOSE_S_ESTABLISH_INTRO:
  541. /* at Bob, waiting for introductions */
  542. if (circ->state != CIRCUIT_STATE_OPEN) {
  543. circuit_increment_failure_count();
  544. }
  545. /* no need to care here, because bob will rebuild intro
  546. * points periodically. */
  547. break;
  548. case CIRCUIT_PURPOSE_C_INTRODUCING:
  549. /* at Alice, connecting to intro point */
  550. /* Don't increment failure count, since Bob may have picked
  551. * the introduction point maliciously */
  552. /* Alice will pick a new intro point when this one dies, if
  553. * the stream in question still cares. No need to act here. */
  554. break;
  555. case CIRCUIT_PURPOSE_C_ESTABLISH_REND:
  556. /* at Alice, waiting for Bob */
  557. if (circ->state != CIRCUIT_STATE_OPEN) {
  558. circuit_increment_failure_count();
  559. }
  560. /* Alice will pick a new rend point when this one dies, if
  561. * the stream in question still cares. No need to act here. */
  562. break;
  563. case CIRCUIT_PURPOSE_S_CONNECT_REND:
  564. /* at Bob, connecting to rend point */
  565. /* Don't increment failure count, since Alice may have picked
  566. * the rendezvous point maliciously */
  567. if (failed_at_last_hop) {
  568. log_fn(LOG_INFO,"Couldn't connect to Alice's chosen rend point %s. Sucks to be Alice.", circ->build_state->chosen_exit_name);
  569. } else {
  570. log_fn(LOG_INFO,"Couldn't connect to Alice's chosen rend point %s, because an earlier node failed.",
  571. circ->build_state->chosen_exit_name);
  572. rend_service_relaunch_rendezvous(circ);
  573. }
  574. break;
  575. default:
  576. /* Other cases are impossible, since this function is only called with
  577. * unbuilt circuits. */
  578. tor_assert(0);
  579. }
  580. }
  581. /** Number of consecutive failures so far; should only be touched by
  582. * circuit_launch_new and circuit_*_failure_count.
  583. */
  584. static int n_circuit_failures = 0;
  585. static int did_circs_fail_last_period = 0;
  586. /** Don't retry launching a new circuit if we try this many times with no
  587. * success. */
  588. #define MAX_CIRCUIT_FAILURES 5
  589. circuit_t *
  590. circuit_launch_by_identity(uint8_t purpose, const char *exit_digest,
  591. int need_uptime, int need_capacity, int internal)
  592. {
  593. circuit_t *circ;
  594. if (!has_fetched_directory) {
  595. log_fn(LOG_DEBUG,"Haven't fetched directory yet; canceling circuit launch.");
  596. return NULL;
  597. }
  598. if (purpose != CIRCUIT_PURPOSE_C_GENERAL) {
  599. /* see if there are appropriate circs available to cannibalize. */
  600. if ((circ = circuit_get_clean_open(CIRCUIT_PURPOSE_C_GENERAL, need_uptime,
  601. need_capacity, internal))) {
  602. log_fn(LOG_INFO,"Cannibalizing circ '%s' for purpose %d",
  603. circ->build_state->chosen_exit_name, purpose);
  604. circ->purpose = purpose;
  605. /* reset the birth date of this circ, else expire_building
  606. * will see it and think it's been trying to build since it
  607. * began. */
  608. circ->timestamp_created = time(NULL);
  609. switch (purpose) {
  610. case CIRCUIT_PURPOSE_C_ESTABLISH_REND:
  611. /* it's ready right now */
  612. /* XXX should we call control_event_circuit_status() here? */
  613. rend_client_rendcirc_has_opened(circ);
  614. break;
  615. case CIRCUIT_PURPOSE_S_ESTABLISH_INTRO:
  616. /* it's ready right now */
  617. rend_service_intro_has_opened(circ);
  618. break;
  619. case CIRCUIT_PURPOSE_C_INTRODUCING:
  620. case CIRCUIT_PURPOSE_S_CONNECT_REND:
  621. /* need to add a new hop */
  622. tor_assert(exit_digest);
  623. if (circuit_append_new_hop(circ, NULL, exit_digest) < 0)
  624. return NULL;
  625. break;
  626. default:
  627. log_fn(LOG_WARN,"Bug: unexpected purpose %d when cannibalizing a general circ.",
  628. purpose);
  629. #ifdef TOR_FRAGILE
  630. tor_assert(0);
  631. #endif
  632. return NULL;
  633. }
  634. return circ;
  635. }
  636. }
  637. if (did_circs_fail_last_period &&
  638. n_circuit_failures > MAX_CIRCUIT_FAILURES) {
  639. /* too many failed circs in a row. don't try. */
  640. // log_fn(LOG_INFO,"%d failures so far, not trying.",n_circuit_failures);
  641. return NULL;
  642. }
  643. /* try a circ. if it fails, circuit_mark_for_close will increment n_circuit_failures */
  644. return circuit_establish_circuit(purpose, exit_digest,
  645. need_uptime, need_capacity, internal);
  646. }
  647. /** Launch a new circuit and return a pointer to it. Return NULL if you failed. */
  648. circuit_t *
  649. circuit_launch_by_nickname(uint8_t purpose, const char *exit_nickname,
  650. int need_uptime, int need_capacity, int internal)
  651. {
  652. const char *digest = NULL;
  653. if (exit_nickname) {
  654. routerinfo_t *r = router_get_by_nickname(exit_nickname);
  655. if (!r) {
  656. log_fn(LOG_WARN, "No such OR as '%s'", exit_nickname);
  657. return NULL;
  658. }
  659. digest = r->identity_digest;
  660. }
  661. return circuit_launch_by_identity(purpose, digest,
  662. need_uptime, need_capacity, internal);
  663. }
  664. /** Record another failure at opening a general circuit. When we have
  665. * too many, we'll stop trying for the remainder of this minute.
  666. */
  667. static void circuit_increment_failure_count(void) {
  668. ++n_circuit_failures;
  669. log_fn(LOG_DEBUG,"n_circuit_failures now %d.",n_circuit_failures);
  670. }
  671. /** Reset the failure count for opening general circuits. This means
  672. * we will try MAX_CIRCUIT_FAILURES times more (if necessary) before
  673. * stopping again.
  674. */
  675. void circuit_reset_failure_count(int timeout) {
  676. if (timeout && n_circuit_failures > MAX_CIRCUIT_FAILURES)
  677. did_circs_fail_last_period = 1;
  678. else
  679. did_circs_fail_last_period = 0;
  680. n_circuit_failures = 0;
  681. }
  682. /** Find an open circ that we're happy with: return 1. If there isn't
  683. * one, and there isn't one on the way, launch one and return 0. If it
  684. * will never work, return -1.
  685. *
  686. * Write the found or in-progress or launched circ into *circp.
  687. */
  688. static int
  689. circuit_get_open_circ_or_launch(connection_t *conn,
  690. uint8_t desired_circuit_purpose,
  691. circuit_t **circp) {
  692. circuit_t *circ;
  693. uint32_t addr;
  694. int is_resolve;
  695. int need_uptime;
  696. tor_assert(conn);
  697. tor_assert(circp);
  698. tor_assert(conn->state == AP_CONN_STATE_CIRCUIT_WAIT);
  699. is_resolve = conn->socks_request->command == SOCKS_COMMAND_RESOLVE;
  700. circ = circuit_get_best(conn, 1, desired_circuit_purpose);
  701. if (circ) {
  702. *circp = circ;
  703. return 1; /* we're happy */
  704. }
  705. if (!has_fetched_directory) {
  706. if (!connection_get_by_type(CONN_TYPE_DIR)) {
  707. log_fn(LOG_NOTICE,"Application request when we're believed to be offline. Optimistically trying again.");
  708. directory_get_from_dirserver(DIR_PURPOSE_FETCH_DIR, NULL, 1);
  709. }
  710. /* the stream will be dealt with when has_fetched_directory becomes
  711. * 1, or when all directory attempts fail and directory_all_unreachable()
  712. * kills it.
  713. */
  714. return 0;
  715. }
  716. need_uptime = smartlist_string_num_isin(get_options()->LongLivedPorts,
  717. conn->socks_request->port);
  718. /* Do we need to check exit policy? */
  719. if (!is_resolve && !connection_edge_is_rendezvous_stream(conn)) {
  720. addr = client_dns_lookup_entry(conn->socks_request->address);
  721. if (router_exit_policy_all_routers_reject(addr, conn->socks_request->port,
  722. need_uptime)) {
  723. log_fn(LOG_NOTICE,"No Tor server exists that allows exit to %s:%d. Rejecting.",
  724. conn->socks_request->address, conn->socks_request->port);
  725. return -1;
  726. }
  727. }
  728. /* is one already on the way? */
  729. circ = circuit_get_best(conn, 0, desired_circuit_purpose);
  730. if (!circ) {
  731. char *exitname=NULL;
  732. uint8_t new_circ_purpose;
  733. int is_internal;
  734. if (desired_circuit_purpose == CIRCUIT_PURPOSE_C_INTRODUCE_ACK_WAIT) {
  735. /* need to pick an intro point */
  736. try_an_intro_point:
  737. exitname = rend_client_get_random_intro(conn->rend_query);
  738. if (!exitname) {
  739. log_fn(LOG_INFO,"No intro points for '%s': refetching service descriptor.",
  740. conn->rend_query);
  741. rend_client_refetch_renddesc(conn->rend_query);
  742. conn->state = AP_CONN_STATE_RENDDESC_WAIT;
  743. return 0;
  744. }
  745. if (!router_get_by_nickname(exitname)) {
  746. log_fn(LOG_NOTICE,"Advertised intro point '%s' is not recognized for '%s'. Skipping over.",
  747. exitname, conn->rend_query);
  748. rend_client_remove_intro_point(exitname, conn->rend_query);
  749. tor_free(exitname);
  750. goto try_an_intro_point;
  751. }
  752. log_fn(LOG_INFO,"Chose %s as intro point for %s.", exitname, conn->rend_query);
  753. }
  754. /* If we have specified a particular exit node for our
  755. * connection, then be sure to open a circuit to that exit node.
  756. */
  757. if (desired_circuit_purpose == CIRCUIT_PURPOSE_C_GENERAL) {
  758. if (conn->chosen_exit_name) {
  759. exitname = tor_strdup(conn->chosen_exit_name);
  760. if (!router_get_by_nickname(exitname)) {
  761. log_fn(LOG_NOTICE,"Requested exit point '%s' is not known. Closing.", exitname);
  762. tor_free(exitname);
  763. return -1;
  764. }
  765. }
  766. }
  767. if (desired_circuit_purpose == CIRCUIT_PURPOSE_C_REND_JOINED)
  768. new_circ_purpose = CIRCUIT_PURPOSE_C_ESTABLISH_REND;
  769. else if (desired_circuit_purpose == CIRCUIT_PURPOSE_C_INTRODUCE_ACK_WAIT)
  770. new_circ_purpose = CIRCUIT_PURPOSE_C_INTRODUCING;
  771. else
  772. new_circ_purpose = desired_circuit_purpose;
  773. is_internal = (new_circ_purpose != CIRCUIT_PURPOSE_C_GENERAL || is_resolve);
  774. circ = circuit_launch_by_nickname(new_circ_purpose, exitname, need_uptime,
  775. 1, is_internal);
  776. tor_free(exitname);
  777. if (desired_circuit_purpose != CIRCUIT_PURPOSE_C_GENERAL) {
  778. /* help predict this next time */
  779. rep_hist_note_used_hidserv(time(NULL), need_uptime, 1);
  780. if (circ) {
  781. /* write the service_id into circ */
  782. strlcpy(circ->rend_query, conn->rend_query, sizeof(circ->rend_query));
  783. }
  784. }
  785. }
  786. if (!circ)
  787. log_fn(LOG_INFO,"No safe circuit (purpose %d) ready for edge connection; delaying.",
  788. desired_circuit_purpose);
  789. *circp = circ;
  790. return 0;
  791. }
  792. /** Attach the AP stream <b>apconn</b> to circ's linked list of
  793. * p_streams. Also set apconn's cpath_layer to the last hop in
  794. * circ's cpath.
  795. */
  796. static void link_apconn_to_circ(connection_t *apconn, circuit_t *circ) {
  797. /* add it into the linked list of streams on this circuit */
  798. log_fn(LOG_DEBUG,"attaching new conn to circ. n_circ_id %d.", circ->n_circ_id);
  799. apconn->timestamp_lastread = time(NULL); /* reset it, so we can measure circ timeouts */
  800. apconn->next_stream = circ->p_streams;
  801. /* assert_connection_ok(conn, time(NULL)); */
  802. circ->p_streams = apconn;
  803. tor_assert(CIRCUIT_IS_ORIGIN(circ));
  804. tor_assert(circ->cpath);
  805. tor_assert(circ->cpath->prev);
  806. tor_assert(circ->cpath->prev->state == CPATH_STATE_OPEN);
  807. apconn->cpath_layer = circ->cpath->prev;
  808. }
  809. /** Try to find a safe live circuit for CONN_TYPE_AP connection conn. If
  810. * we don't find one: if conn cannot be handled by any known nodes,
  811. * warn and return -1 (conn needs to die);
  812. * else launch new circuit (if necessary) and return 0.
  813. * Otherwise, associate conn with a safe live circuit, do the
  814. * right next step, and return 1.
  815. */
  816. int connection_ap_handshake_attach_circuit(connection_t *conn) {
  817. int retval;
  818. int conn_age;
  819. tor_assert(conn);
  820. tor_assert(conn->type == CONN_TYPE_AP);
  821. tor_assert(conn->state == AP_CONN_STATE_CIRCUIT_WAIT);
  822. tor_assert(conn->socks_request);
  823. conn_age = time(NULL) - conn->timestamp_created;
  824. if (conn_age > CONN_AP_MAX_ATTACH_DELAY) {
  825. log_fn(LOG_NOTICE,"Giving up on unattached conn (%d sec old).", conn_age);
  826. return -1;
  827. }
  828. if (!connection_edge_is_rendezvous_stream(conn)) { /* we're a general conn */
  829. circuit_t *circ=NULL;
  830. if (conn->chosen_exit_name) {
  831. routerinfo_t *router = router_get_by_nickname(conn->chosen_exit_name);
  832. if (!router) {
  833. log_fn(LOG_WARN,"Requested exit point '%s' is not known. Closing.",
  834. conn->chosen_exit_name);
  835. return -1;
  836. }
  837. if (!connection_ap_can_use_exit(conn, router)) {
  838. log_fn(LOG_WARN, "Requested exit point '%s' would refuse request. Closing.",
  839. conn->chosen_exit_name);
  840. return -1;
  841. }
  842. }
  843. /* find the circuit that we should use, if there is one. */
  844. retval = circuit_get_open_circ_or_launch(conn, CIRCUIT_PURPOSE_C_GENERAL, &circ);
  845. if (retval < 1)
  846. return retval;
  847. /* We have found a suitable circuit for our conn. Hurray. */
  848. tor_assert(circ);
  849. log_fn(LOG_DEBUG,"Attaching apconn to general circ %d (stream %d sec old).",
  850. circ->n_circ_id, conn_age);
  851. /* here, print the circ's path. so people can figure out which circs are sucking. */
  852. circuit_log_path(LOG_INFO,circ);
  853. if (!circ->timestamp_dirty)
  854. circ->timestamp_dirty = time(NULL);
  855. link_apconn_to_circ(conn, circ);
  856. tor_assert(conn->socks_request);
  857. if (conn->socks_request->command == SOCKS_COMMAND_CONNECT)
  858. connection_ap_handshake_send_begin(conn, circ);
  859. else
  860. connection_ap_handshake_send_resolve(conn, circ);
  861. return 1;
  862. } else { /* we're a rendezvous conn */
  863. circuit_t *rendcirc=NULL, *introcirc=NULL;
  864. tor_assert(!conn->cpath_layer);
  865. /* start by finding a rendezvous circuit for us */
  866. retval = circuit_get_open_circ_or_launch(conn, CIRCUIT_PURPOSE_C_REND_JOINED, &rendcirc);
  867. if (retval < 0) return -1; /* failed */
  868. if (retval > 0) {
  869. tor_assert(rendcirc);
  870. /* one is already established, attach */
  871. log_fn(LOG_INFO,"rend joined circ %d already here. attaching. (stream %d sec old)",
  872. rendcirc->n_circ_id, conn_age);
  873. /* Mark rendezvous circuits as 'newly dirty' every time you use
  874. * them, since the process of rebuilding a rendezvous circ is so
  875. * expensive. There is a tradeoffs between linkability and
  876. * feasibility, at this point.
  877. */
  878. rendcirc->timestamp_dirty = time(NULL);
  879. link_apconn_to_circ(conn, rendcirc);
  880. if (connection_ap_handshake_send_begin(conn, rendcirc) < 0)
  881. return 0; /* already marked, let them fade away */
  882. return 1;
  883. }
  884. if (rendcirc && rendcirc->purpose == CIRCUIT_PURPOSE_C_REND_READY_INTRO_ACKED) {
  885. log_fn(LOG_INFO,"pending-join circ %d already here, with intro ack. Stalling. (stream %d sec old)", rendcirc->n_circ_id, conn_age);
  886. return 0;
  887. }
  888. /* it's on its way. find an intro circ. */
  889. retval = circuit_get_open_circ_or_launch(conn, CIRCUIT_PURPOSE_C_INTRODUCE_ACK_WAIT, &introcirc);
  890. if (retval < 0) return -1; /* failed */
  891. if (retval > 0) {
  892. /* one has already sent the intro. keep waiting. */
  893. tor_assert(introcirc);
  894. log_fn(LOG_INFO,"Intro circ %d present and awaiting ack (rend %d). Stalling. (stream %d sec old)",
  895. introcirc->n_circ_id, rendcirc ? rendcirc->n_circ_id : 0, conn_age);
  896. return 0;
  897. }
  898. /* now rendcirc and introcirc are each either undefined or not finished */
  899. if (rendcirc && introcirc && rendcirc->purpose == CIRCUIT_PURPOSE_C_REND_READY) {
  900. log_fn(LOG_INFO,"ready rend circ %d already here (no intro-ack yet on intro %d). (stream %d sec old)",
  901. rendcirc->n_circ_id, introcirc->n_circ_id, conn_age);
  902. tor_assert(introcirc->purpose == CIRCUIT_PURPOSE_C_INTRODUCING);
  903. if (introcirc->state == CIRCUIT_STATE_OPEN) {
  904. log_fn(LOG_INFO,"found open intro circ %d (rend %d); sending introduction. (stream %d sec old)",
  905. introcirc->n_circ_id, rendcirc->n_circ_id, conn_age);
  906. if (rend_client_send_introduction(introcirc, rendcirc) < 0) {
  907. return -1;
  908. }
  909. rendcirc->timestamp_dirty = time(NULL);
  910. introcirc->timestamp_dirty = time(NULL);
  911. assert_circuit_ok(rendcirc);
  912. assert_circuit_ok(introcirc);
  913. return 0;
  914. }
  915. }
  916. log_fn(LOG_INFO,"Intro (%d) and rend (%d) circs are not both ready. Stalling conn. (%d sec old)",
  917. introcirc ? introcirc->n_circ_id : 0,
  918. rendcirc ? rendcirc->n_circ_id : 0, conn_age);
  919. return 0;
  920. }
  921. }