circuituse.c 46 KB

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