circuituse.c 53 KB

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