circuituse.c 42 KB

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