circuituse.c 47 KB

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