circuituse.c 55 KB

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