circuituse.c 49 KB

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