circuituse.c 55 KB

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