circuituse.c 43 KB

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