circuituse.c 55 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539
  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-2009, 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 purpose %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 purpose %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 hidden service 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 time_t 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, "
  582. "purpose %d)",
  583. circ->n_circ_id, (int)(now - circ->timestamp_dirty),
  584. circ->purpose);
  585. circuit_mark_for_close(circ, END_CIRC_REASON_FINISHED);
  586. } else if (!circ->timestamp_dirty &&
  587. circ->state == CIRCUIT_STATE_OPEN &&
  588. circ->purpose == CIRCUIT_PURPOSE_C_GENERAL) {
  589. if (circ->timestamp_created < cutoff) {
  590. log_debug(LD_CIRC,
  591. "Closing circuit that has been unused for %d seconds.",
  592. (int)(now - circ->timestamp_created));
  593. circuit_mark_for_close(circ, END_CIRC_REASON_FINISHED);
  594. }
  595. }
  596. }
  597. }
  598. /** Number of testing circuits we want open before testing our bandwidth. */
  599. #define NUM_PARALLEL_TESTING_CIRCS 4
  600. /** True iff we've ever had enough testing circuits open to test our
  601. * bandwidth. */
  602. static int have_performed_bandwidth_test = 0;
  603. /** Reset have_performed_bandwidth_test, so we'll start building
  604. * testing circuits again so we can exercise our bandwidth. */
  605. void
  606. reset_bandwidth_test(void)
  607. {
  608. have_performed_bandwidth_test = 0;
  609. }
  610. /** Return 1 if we've already exercised our bandwidth, or if we
  611. * have fewer than NUM_PARALLEL_TESTING_CIRCS testing circuits
  612. * established or on the way. Else return 0.
  613. */
  614. int
  615. circuit_enough_testing_circs(void)
  616. {
  617. circuit_t *circ;
  618. int num = 0;
  619. if (have_performed_bandwidth_test)
  620. return 1;
  621. for (circ = global_circuitlist; circ; circ = circ->next) {
  622. if (!circ->marked_for_close && CIRCUIT_IS_ORIGIN(circ) &&
  623. circ->purpose == CIRCUIT_PURPOSE_TESTING &&
  624. circ->state == CIRCUIT_STATE_OPEN)
  625. num++;
  626. }
  627. return num >= NUM_PARALLEL_TESTING_CIRCS;
  628. }
  629. /** A testing circuit has completed. Take whatever stats we want.
  630. * Noticing reachability is taken care of in onionskin_answer(),
  631. * so there's no need to record anything here. But if we still want
  632. * to do the bandwidth test, and we now have enough testing circuits
  633. * open, do it.
  634. */
  635. static void
  636. circuit_testing_opened(origin_circuit_t *circ)
  637. {
  638. if (have_performed_bandwidth_test ||
  639. !check_whether_orport_reachable()) {
  640. /* either we've already done everything we want with testing circuits,
  641. * or this testing circuit became open due to a fluke, e.g. we picked
  642. * a last hop where we already had the connection open due to an
  643. * outgoing local circuit. */
  644. circuit_mark_for_close(TO_CIRCUIT(circ), END_CIRC_AT_ORIGIN);
  645. } else if (circuit_enough_testing_circs()) {
  646. router_perform_bandwidth_test(NUM_PARALLEL_TESTING_CIRCS, time(NULL));
  647. have_performed_bandwidth_test = 1;
  648. } else
  649. consider_testing_reachability(1, 0);
  650. }
  651. /** A testing circuit has failed to build. Take whatever stats we want. */
  652. static void
  653. circuit_testing_failed(origin_circuit_t *circ, int at_last_hop)
  654. {
  655. routerinfo_t *me = router_get_my_routerinfo();
  656. if (server_mode(get_options()) && check_whether_orport_reachable())
  657. return;
  658. if (!me)
  659. return;
  660. log_info(LD_GENERAL,
  661. "Our testing circuit (to see if your ORPort is reachable) "
  662. "has failed. I'll try again later.");
  663. control_event_server_status(LOG_WARN, "REACHABILITY_FAILED ORADDRESS=%s:%d",
  664. me->address, me->or_port);
  665. /* These aren't used yet. */
  666. (void)circ;
  667. (void)at_last_hop;
  668. }
  669. /** The circuit <b>circ</b> has just become open. Take the next
  670. * step: for rendezvous circuits, we pass circ to the appropriate
  671. * function in rendclient or rendservice. For general circuits, we
  672. * call connection_ap_attach_pending, which looks for pending streams
  673. * that could use circ.
  674. */
  675. void
  676. circuit_has_opened(origin_circuit_t *circ)
  677. {
  678. control_event_circuit_status(circ, CIRC_EVENT_BUILT, 0);
  679. switch (TO_CIRCUIT(circ)->purpose) {
  680. case CIRCUIT_PURPOSE_C_ESTABLISH_REND:
  681. rend_client_rendcirc_has_opened(circ);
  682. connection_ap_attach_pending();
  683. break;
  684. case CIRCUIT_PURPOSE_C_INTRODUCING:
  685. rend_client_introcirc_has_opened(circ);
  686. break;
  687. case CIRCUIT_PURPOSE_C_GENERAL:
  688. /* Tell any AP connections that have been waiting for a new
  689. * circuit that one is ready. */
  690. connection_ap_attach_pending();
  691. break;
  692. case CIRCUIT_PURPOSE_S_ESTABLISH_INTRO:
  693. /* at Bob, waiting for introductions */
  694. rend_service_intro_has_opened(circ);
  695. break;
  696. case CIRCUIT_PURPOSE_S_CONNECT_REND:
  697. /* at Bob, connecting to rend point */
  698. rend_service_rendezvous_has_opened(circ);
  699. break;
  700. case CIRCUIT_PURPOSE_TESTING:
  701. circuit_testing_opened(circ);
  702. break;
  703. /* default:
  704. * This won't happen in normal operation, but might happen if the
  705. * controller did it. Just let it slide. */
  706. }
  707. }
  708. /** Called whenever a circuit could not be successfully built.
  709. */
  710. void
  711. circuit_build_failed(origin_circuit_t *circ)
  712. {
  713. /* we should examine circ and see if it failed because of
  714. * the last hop or an earlier hop. then use this info below.
  715. */
  716. int failed_at_last_hop = 0;
  717. /* If the last hop isn't open, and the second-to-last is, we failed
  718. * at the last hop. */
  719. if (circ->cpath &&
  720. circ->cpath->prev->state != CPATH_STATE_OPEN &&
  721. circ->cpath->prev->prev->state == CPATH_STATE_OPEN) {
  722. failed_at_last_hop = 1;
  723. }
  724. if (circ->cpath &&
  725. circ->cpath->state != CPATH_STATE_OPEN) {
  726. /* We failed at the first hop. If there's an OR connection
  727. * to blame, blame it. Also, avoid this relay for a while, and
  728. * fail any one-hop directory fetches destined for it. */
  729. const char *n_conn_id = circ->cpath->extend_info->identity_digest;
  730. if (circ->_base.n_conn) {
  731. or_connection_t *n_conn = circ->_base.n_conn;
  732. log_info(LD_OR,
  733. "Our circuit failed to get a response from the first hop "
  734. "(%s:%d). I'm going to try to rotate to a better connection.",
  735. n_conn->_base.address, n_conn->_base.port);
  736. n_conn->is_bad_for_new_circs = 1;
  737. }
  738. if (n_conn_id) {
  739. entry_guard_register_connect_status(n_conn_id, 0, 1, time(NULL));
  740. /* if there are any one-hop streams waiting on this circuit, fail
  741. * them now so they can retry elsewhere. */
  742. connection_ap_fail_onehop(n_conn_id, circ->build_state);
  743. }
  744. }
  745. switch (circ->_base.purpose) {
  746. case CIRCUIT_PURPOSE_C_GENERAL:
  747. /* If we never built the circuit, note it as a failure. */
  748. circuit_increment_failure_count();
  749. if (failed_at_last_hop) {
  750. /* Make sure any streams that demand our last hop as their exit
  751. * know that it's unlikely to happen. */
  752. circuit_discard_optional_exit_enclaves(circ->cpath->prev->extend_info);
  753. }
  754. break;
  755. case CIRCUIT_PURPOSE_TESTING:
  756. circuit_testing_failed(circ, failed_at_last_hop);
  757. break;
  758. case CIRCUIT_PURPOSE_S_ESTABLISH_INTRO:
  759. /* at Bob, waiting for introductions */
  760. if (circ->_base.state != CIRCUIT_STATE_OPEN) {
  761. circuit_increment_failure_count();
  762. }
  763. /* no need to care here, because bob will rebuild intro
  764. * points periodically. */
  765. break;
  766. case CIRCUIT_PURPOSE_C_INTRODUCING:
  767. /* at Alice, connecting to intro point */
  768. /* Don't increment failure count, since Bob may have picked
  769. * the introduction point maliciously */
  770. /* Alice will pick a new intro point when this one dies, if
  771. * the stream in question still cares. No need to act here. */
  772. break;
  773. case CIRCUIT_PURPOSE_C_ESTABLISH_REND:
  774. /* at Alice, waiting for Bob */
  775. circuit_increment_failure_count();
  776. /* Alice will pick a new rend point when this one dies, if
  777. * the stream in question still cares. No need to act here. */
  778. break;
  779. case CIRCUIT_PURPOSE_S_CONNECT_REND:
  780. /* at Bob, connecting to rend point */
  781. /* Don't increment failure count, since Alice may have picked
  782. * the rendezvous point maliciously */
  783. log_info(LD_REND,
  784. "Couldn't connect to Alice's chosen rend point %s "
  785. "(%s hop failed).",
  786. escaped(build_state_get_exit_nickname(circ->build_state)),
  787. failed_at_last_hop?"last":"non-last");
  788. rend_service_relaunch_rendezvous(circ);
  789. break;
  790. /* default:
  791. * This won't happen in normal operation, but might happen if the
  792. * controller did it. Just let it slide. */
  793. }
  794. }
  795. /** Number of consecutive failures so far; should only be touched by
  796. * circuit_launch_new and circuit_*_failure_count.
  797. */
  798. static int n_circuit_failures = 0;
  799. /** Before the last time we called circuit_reset_failure_count(), were
  800. * there a lot of failures? */
  801. static int did_circs_fail_last_period = 0;
  802. /** Don't retry launching a new circuit if we try this many times with no
  803. * success. */
  804. #define MAX_CIRCUIT_FAILURES 5
  805. /** Launch a new circuit; see circuit_launch_by_extend_info() for
  806. * details on arguments. */
  807. origin_circuit_t *
  808. circuit_launch_by_router(uint8_t purpose,
  809. routerinfo_t *exit, int flags)
  810. {
  811. origin_circuit_t *circ;
  812. extend_info_t *info = NULL;
  813. if (exit)
  814. info = extend_info_from_router(exit);
  815. circ = circuit_launch_by_extend_info(purpose, info, flags);
  816. if (info)
  817. extend_info_free(info);
  818. return circ;
  819. }
  820. /** Launch a new circuit with purpose <b>purpose</b> and exit node
  821. * <b>extend_info</b> (or NULL to select a random exit node). If flags
  822. * contains CIRCLAUNCH_NEED_UPTIME, choose among routers with high uptime. If
  823. * CIRCLAUNCH_NEED_CAPACITY is set, choose among routers with high bandwidth.
  824. * If CIRCLAUNCH_IS_INTERNAL is true, the last hop need not be an exit node.
  825. * If CIRCLAUNCH_ONEHOP_TUNNEL is set, the circuit will have only one hop.
  826. * Return the newly allocated circuit on success, or NULL on failure. */
  827. origin_circuit_t *
  828. circuit_launch_by_extend_info(uint8_t purpose,
  829. extend_info_t *extend_info,
  830. int flags)
  831. {
  832. origin_circuit_t *circ;
  833. int onehop_tunnel = (flags & CIRCLAUNCH_ONEHOP_TUNNEL) != 0;
  834. if (!onehop_tunnel && !router_have_minimum_dir_info()) {
  835. log_debug(LD_CIRC,"Haven't fetched enough directory info yet; canceling "
  836. "circuit launch.");
  837. return NULL;
  838. }
  839. if ((extend_info || purpose != CIRCUIT_PURPOSE_C_GENERAL) &&
  840. purpose != CIRCUIT_PURPOSE_TESTING && !onehop_tunnel) {
  841. /* see if there are appropriate circs available to cannibalize. */
  842. /* XXX if we're planning to add a hop, perhaps we want to look for
  843. * internal circs rather than exit circs? -RD */
  844. circ = circuit_find_to_cannibalize(purpose, extend_info, flags);
  845. if (circ) {
  846. log_info(LD_CIRC,"Cannibalizing circ '%s' for purpose %d",
  847. build_state_get_exit_nickname(circ->build_state), purpose);
  848. circ->_base.purpose = purpose;
  849. /* reset the birth date of this circ, else expire_building
  850. * will see it and think it's been trying to build since it
  851. * began. */
  852. circ->_base.timestamp_created = time(NULL);
  853. switch (purpose) {
  854. case CIRCUIT_PURPOSE_C_ESTABLISH_REND:
  855. case CIRCUIT_PURPOSE_S_ESTABLISH_INTRO:
  856. /* it's ready right now */
  857. break;
  858. case CIRCUIT_PURPOSE_C_INTRODUCING:
  859. case CIRCUIT_PURPOSE_S_CONNECT_REND:
  860. case CIRCUIT_PURPOSE_C_GENERAL:
  861. /* need to add a new hop */
  862. tor_assert(extend_info);
  863. if (circuit_extend_to_new_exit(circ, extend_info) < 0)
  864. return NULL;
  865. break;
  866. default:
  867. log_warn(LD_BUG,
  868. "unexpected purpose %d when cannibalizing a circ.",
  869. purpose);
  870. tor_fragile_assert();
  871. return NULL;
  872. }
  873. return circ;
  874. }
  875. }
  876. if (did_circs_fail_last_period &&
  877. n_circuit_failures > MAX_CIRCUIT_FAILURES) {
  878. /* too many failed circs in a row. don't try. */
  879. // log_fn(LOG_INFO,"%d failures so far, not trying.",n_circuit_failures);
  880. return NULL;
  881. }
  882. /* try a circ. if it fails, circuit_mark_for_close will increment
  883. * n_circuit_failures */
  884. return circuit_establish_circuit(purpose, extend_info, flags);
  885. }
  886. /** Record another failure at opening a general circuit. When we have
  887. * too many, we'll stop trying for the remainder of this minute.
  888. */
  889. static void
  890. circuit_increment_failure_count(void)
  891. {
  892. ++n_circuit_failures;
  893. log_debug(LD_CIRC,"n_circuit_failures now %d.",n_circuit_failures);
  894. }
  895. /** Reset the failure count for opening general circuits. This means
  896. * we will try MAX_CIRCUIT_FAILURES times more (if necessary) before
  897. * stopping again.
  898. */
  899. void
  900. circuit_reset_failure_count(int timeout)
  901. {
  902. if (timeout && n_circuit_failures > MAX_CIRCUIT_FAILURES)
  903. did_circs_fail_last_period = 1;
  904. else
  905. did_circs_fail_last_period = 0;
  906. n_circuit_failures = 0;
  907. }
  908. /** Find an open circ that we're happy to use for <b>conn</b> and return 1. If
  909. * there isn't one, and there isn't one on the way, launch one and return
  910. * 0. If it will never work, return -1.
  911. *
  912. * Write the found or in-progress or launched circ into *circp.
  913. */
  914. static int
  915. circuit_get_open_circ_or_launch(edge_connection_t *conn,
  916. uint8_t desired_circuit_purpose,
  917. origin_circuit_t **circp)
  918. {
  919. origin_circuit_t *circ;
  920. int check_exit_policy;
  921. int need_uptime, need_internal;
  922. int want_onehop;
  923. or_options_t *options = get_options();
  924. tor_assert(conn);
  925. tor_assert(circp);
  926. tor_assert(conn->_base.state == AP_CONN_STATE_CIRCUIT_WAIT);
  927. check_exit_policy =
  928. conn->socks_request->command == SOCKS_COMMAND_CONNECT &&
  929. !conn->use_begindir &&
  930. !connection_edge_is_rendezvous_stream(conn);
  931. want_onehop = conn->want_onehop;
  932. need_uptime = !conn->want_onehop && !conn->use_begindir &&
  933. smartlist_string_num_isin(options->LongLivedPorts,
  934. conn->socks_request->port);
  935. need_internal = desired_circuit_purpose != CIRCUIT_PURPOSE_C_GENERAL;
  936. circ = circuit_get_best(conn, 1, desired_circuit_purpose,
  937. need_uptime, need_internal);
  938. if (circ) {
  939. *circp = circ;
  940. return 1; /* we're happy */
  941. }
  942. if (!want_onehop && !router_have_minimum_dir_info()) {
  943. if (!connection_get_by_type(CONN_TYPE_DIR)) {
  944. int severity = LOG_NOTICE;
  945. /* FFFF if this is a tunneled directory fetch, don't yell
  946. * as loudly. the user doesn't even know it's happening. */
  947. if (options->UseBridges && bridges_known_but_down()) {
  948. log_fn(severity, LD_APP|LD_DIR,
  949. "Application request when we're believed to be "
  950. "offline. Optimistically trying known bridges again.");
  951. bridges_retry_all();
  952. } else if (!options->UseBridges || any_bridge_descriptors_known()) {
  953. log_fn(severity, LD_APP|LD_DIR,
  954. "Application request when we're believed to be "
  955. "offline. Optimistically trying directory fetches again.");
  956. routerlist_retry_directory_downloads(time(NULL));
  957. }
  958. }
  959. /* the stream will be dealt with when router_have_minimum_dir_info becomes
  960. * 1, or when all directory attempts fail and directory_all_unreachable()
  961. * kills it.
  962. */
  963. return 0;
  964. }
  965. /* Do we need to check exit policy? */
  966. if (check_exit_policy) {
  967. if (!conn->chosen_exit_name) {
  968. struct in_addr in;
  969. uint32_t addr = 0;
  970. if (tor_inet_aton(conn->socks_request->address, &in))
  971. addr = ntohl(in.s_addr);
  972. if (router_exit_policy_all_routers_reject(addr,
  973. conn->socks_request->port,
  974. need_uptime)) {
  975. log_notice(LD_APP,
  976. "No Tor server allows exit to %s:%d. Rejecting.",
  977. safe_str(conn->socks_request->address),
  978. conn->socks_request->port);
  979. return -1;
  980. }
  981. } else {
  982. /* XXXX022 Duplicates checks in connection_ap_handshake_attach_circuit */
  983. routerinfo_t *router = router_get_by_nickname(conn->chosen_exit_name, 1);
  984. int opt = conn->chosen_exit_optional;
  985. if (router && !connection_ap_can_use_exit(conn, router)) {
  986. log_fn(opt ? LOG_INFO : LOG_WARN, LD_APP,
  987. "Requested exit point '%s' would refuse request. %s.",
  988. conn->chosen_exit_name, opt ? "Trying others" : "Closing");
  989. if (opt) {
  990. conn->chosen_exit_optional = 0;
  991. tor_free(conn->chosen_exit_name);
  992. /* Try again. */
  993. return circuit_get_open_circ_or_launch(conn,
  994. desired_circuit_purpose,
  995. circp);
  996. }
  997. return -1;
  998. }
  999. }
  1000. }
  1001. /* is one already on the way? */
  1002. circ = circuit_get_best(conn, 0, desired_circuit_purpose,
  1003. need_uptime, need_internal);
  1004. if (circ)
  1005. log_debug(LD_CIRC, "one on the way!");
  1006. if (!circ) {
  1007. extend_info_t *extend_info=NULL;
  1008. uint8_t new_circ_purpose;
  1009. if (desired_circuit_purpose == CIRCUIT_PURPOSE_C_INTRODUCE_ACK_WAIT) {
  1010. /* need to pick an intro point */
  1011. tor_assert(conn->rend_data);
  1012. extend_info = rend_client_get_random_intro(conn->rend_data);
  1013. if (!extend_info) {
  1014. log_info(LD_REND,
  1015. "No intro points for '%s': re-fetching service descriptor.",
  1016. safe_str(conn->rend_data->onion_address));
  1017. /* Fetch both, v0 and v2 rend descriptors in parallel. Use whichever
  1018. * arrives first. Exception: When using client authorization, only
  1019. * fetch v2 descriptors.*/
  1020. rend_client_refetch_v2_renddesc(conn->rend_data);
  1021. if (conn->rend_data->auth_type == REND_NO_AUTH)
  1022. rend_client_refetch_renddesc(conn->rend_data->onion_address);
  1023. conn->_base.state = AP_CONN_STATE_RENDDESC_WAIT;
  1024. return 0;
  1025. }
  1026. log_info(LD_REND,"Chose '%s' as intro point for '%s'.",
  1027. extend_info->nickname,
  1028. safe_str(conn->rend_data->onion_address));
  1029. }
  1030. /* If we have specified a particular exit node for our
  1031. * connection, then be sure to open a circuit to that exit node.
  1032. */
  1033. if (desired_circuit_purpose == CIRCUIT_PURPOSE_C_GENERAL) {
  1034. if (conn->chosen_exit_name) {
  1035. routerinfo_t *r;
  1036. int opt = conn->chosen_exit_optional;
  1037. r = router_get_by_nickname(conn->chosen_exit_name, 1);
  1038. if (r) {
  1039. extend_info = extend_info_from_router(r);
  1040. } else {
  1041. log_debug(LD_DIR, "considering %d, %s",
  1042. want_onehop, conn->chosen_exit_name);
  1043. if (want_onehop && conn->chosen_exit_name[0] == '$') {
  1044. /* We're asking for a one-hop circuit to a router that
  1045. * we don't have a routerinfo about. Make up an extend_info. */
  1046. char digest[DIGEST_LEN];
  1047. char *hexdigest = conn->chosen_exit_name+1;
  1048. tor_addr_t addr;
  1049. if (strlen(hexdigest) < HEX_DIGEST_LEN ||
  1050. base16_decode(digest,DIGEST_LEN,hexdigest,HEX_DIGEST_LEN)<0) {
  1051. log_info(LD_DIR, "Broken exit digest on tunnel conn. Closing.");
  1052. return -1;
  1053. }
  1054. if (tor_addr_from_str(&addr, conn->socks_request->address) < 0) {
  1055. log_info(LD_DIR, "Broken address %s on tunnel conn. Closing.",
  1056. escaped_safe_str(conn->socks_request->address));
  1057. return -1;
  1058. }
  1059. extend_info = extend_info_alloc(conn->chosen_exit_name+1,
  1060. digest, NULL, &addr,
  1061. conn->socks_request->port);
  1062. } else {
  1063. /* We will need an onion key for the router, and we
  1064. * don't have one. Refuse or relax requirements. */
  1065. log_fn(opt ? LOG_INFO : LOG_WARN, LD_APP,
  1066. "Requested exit point '%s' is not known. %s.",
  1067. conn->chosen_exit_name, opt ? "Trying others" : "Closing");
  1068. if (opt) {
  1069. conn->chosen_exit_optional = 0;
  1070. tor_free(conn->chosen_exit_name);
  1071. /* Try again with no requested exit */
  1072. return circuit_get_open_circ_or_launch(conn,
  1073. desired_circuit_purpose,
  1074. circp);
  1075. }
  1076. return -1;
  1077. }
  1078. }
  1079. }
  1080. }
  1081. if (desired_circuit_purpose == CIRCUIT_PURPOSE_C_REND_JOINED)
  1082. new_circ_purpose = CIRCUIT_PURPOSE_C_ESTABLISH_REND;
  1083. else if (desired_circuit_purpose == CIRCUIT_PURPOSE_C_INTRODUCE_ACK_WAIT)
  1084. new_circ_purpose = CIRCUIT_PURPOSE_C_INTRODUCING;
  1085. else
  1086. new_circ_purpose = desired_circuit_purpose;
  1087. {
  1088. int flags = CIRCLAUNCH_NEED_CAPACITY;
  1089. if (want_onehop) flags |= CIRCLAUNCH_ONEHOP_TUNNEL;
  1090. if (need_uptime) flags |= CIRCLAUNCH_NEED_UPTIME;
  1091. if (need_internal) flags |= CIRCLAUNCH_IS_INTERNAL;
  1092. circ = circuit_launch_by_extend_info(new_circ_purpose, extend_info,
  1093. flags);
  1094. }
  1095. if (extend_info)
  1096. extend_info_free(extend_info);
  1097. if (desired_circuit_purpose != CIRCUIT_PURPOSE_C_GENERAL) {
  1098. /* help predict this next time */
  1099. rep_hist_note_used_internal(time(NULL), need_uptime, 1);
  1100. if (circ) {
  1101. /* write the service_id into circ */
  1102. circ->rend_data = rend_data_dup(conn->rend_data);
  1103. if (circ->_base.purpose == CIRCUIT_PURPOSE_C_ESTABLISH_REND &&
  1104. circ->_base.state == CIRCUIT_STATE_OPEN)
  1105. rend_client_rendcirc_has_opened(circ);
  1106. }
  1107. }
  1108. }
  1109. if (!circ)
  1110. log_info(LD_APP,
  1111. "No safe circuit (purpose %d) ready for edge "
  1112. "connection; delaying.",
  1113. desired_circuit_purpose);
  1114. *circp = circ;
  1115. return 0;
  1116. }
  1117. /** Return true iff <b>crypt_path</b> is one of the crypt_paths for
  1118. * <b>circ</b>. */
  1119. static int
  1120. cpath_is_on_circuit(origin_circuit_t *circ, crypt_path_t *crypt_path)
  1121. {
  1122. crypt_path_t *cpath, *cpath_next = NULL;
  1123. for (cpath = circ->cpath; cpath_next != circ->cpath; cpath = cpath_next) {
  1124. cpath_next = cpath->next;
  1125. if (crypt_path == cpath)
  1126. return 1;
  1127. }
  1128. return 0;
  1129. }
  1130. /** Attach the AP stream <b>apconn</b> to circ's linked list of
  1131. * p_streams. Also set apconn's cpath_layer to <b>cpath</b>, or to the last
  1132. * hop in circ's cpath if <b>cpath</b> is NULL.
  1133. */
  1134. static void
  1135. link_apconn_to_circ(edge_connection_t *apconn, origin_circuit_t *circ,
  1136. crypt_path_t *cpath)
  1137. {
  1138. /* add it into the linked list of streams on this circuit */
  1139. log_debug(LD_APP|LD_CIRC, "attaching new conn to circ. n_circ_id %d.",
  1140. circ->_base.n_circ_id);
  1141. /* reset it, so we can measure circ timeouts */
  1142. apconn->_base.timestamp_lastread = time(NULL);
  1143. apconn->next_stream = circ->p_streams;
  1144. apconn->on_circuit = TO_CIRCUIT(circ);
  1145. /* assert_connection_ok(conn, time(NULL)); */
  1146. circ->p_streams = apconn;
  1147. if (cpath) { /* we were given one; use it */
  1148. tor_assert(cpath_is_on_circuit(circ, cpath));
  1149. apconn->cpath_layer = cpath;
  1150. } else { /* use the last hop in the circuit */
  1151. tor_assert(circ->cpath);
  1152. tor_assert(circ->cpath->prev);
  1153. tor_assert(circ->cpath->prev->state == CPATH_STATE_OPEN);
  1154. apconn->cpath_layer = circ->cpath->prev;
  1155. }
  1156. }
  1157. /** If an exit wasn't specifically chosen, save the history for future
  1158. * use. */
  1159. static void
  1160. consider_recording_trackhost(edge_connection_t *conn, origin_circuit_t *circ)
  1161. {
  1162. int found_needle = 0;
  1163. or_options_t *options = get_options();
  1164. size_t len;
  1165. char *new_address;
  1166. char fp[HEX_DIGEST_LEN+1];
  1167. /* Search the addressmap for this conn's destination. */
  1168. /* If he's not in the address map.. */
  1169. if (!options->TrackHostExits ||
  1170. addressmap_have_mapping(conn->socks_request->address,
  1171. options->TrackHostExitsExpire))
  1172. return; /* nothing to track, or already mapped */
  1173. SMARTLIST_FOREACH(options->TrackHostExits, const char *, cp, {
  1174. if (cp[0] == '.') { /* match end */
  1175. if (cp[1] == '\0' ||
  1176. !strcasecmpend(conn->socks_request->address, cp) ||
  1177. !strcasecmp(conn->socks_request->address, &cp[1]))
  1178. found_needle = 1;
  1179. } else if (strcasecmp(cp, conn->socks_request->address) == 0) {
  1180. found_needle = 1;
  1181. }
  1182. });
  1183. if (!found_needle || !circ->build_state->chosen_exit)
  1184. return;
  1185. /* write down the fingerprint of the chosen exit, not the nickname,
  1186. * because the chosen exit might not be named. */
  1187. base16_encode(fp, sizeof(fp),
  1188. circ->build_state->chosen_exit->identity_digest, DIGEST_LEN);
  1189. /* Add this exit/hostname pair to the addressmap. */
  1190. len = strlen(conn->socks_request->address) + 1 /* '.' */ +
  1191. strlen(fp) + 1 /* '.' */ +
  1192. strlen("exit") + 1 /* '\0' */;
  1193. new_address = tor_malloc(len);
  1194. tor_snprintf(new_address, len, "%s.%s.exit",
  1195. conn->socks_request->address, fp);
  1196. addressmap_register(conn->socks_request->address, new_address,
  1197. time(NULL) + options->TrackHostExitsExpire,
  1198. ADDRMAPSRC_TRACKEXIT);
  1199. }
  1200. /** Attempt to attach the connection <b>conn</b> to <b>circ</b>, and send a
  1201. * begin or resolve cell as appropriate. Return values are as for
  1202. * connection_ap_handshake_attach_circuit. The stream will exit from the hop
  1203. * indicated by <b>cpath</b>, or from the last hop in circ's cpath if
  1204. * <b>cpath</b> is NULL. */
  1205. int
  1206. connection_ap_handshake_attach_chosen_circuit(edge_connection_t *conn,
  1207. origin_circuit_t *circ,
  1208. crypt_path_t *cpath)
  1209. {
  1210. tor_assert(conn);
  1211. tor_assert(conn->_base.state == AP_CONN_STATE_CIRCUIT_WAIT ||
  1212. conn->_base.state == AP_CONN_STATE_CONTROLLER_WAIT);
  1213. tor_assert(conn->socks_request);
  1214. tor_assert(circ);
  1215. tor_assert(circ->_base.state == CIRCUIT_STATE_OPEN);
  1216. conn->_base.state = AP_CONN_STATE_CIRCUIT_WAIT;
  1217. if (!circ->_base.timestamp_dirty)
  1218. circ->_base.timestamp_dirty = time(NULL);
  1219. link_apconn_to_circ(conn, circ, cpath);
  1220. tor_assert(conn->socks_request);
  1221. if (conn->socks_request->command == SOCKS_COMMAND_CONNECT) {
  1222. if (!conn->use_begindir)
  1223. consider_recording_trackhost(conn, circ);
  1224. if (connection_ap_handshake_send_begin(conn) < 0)
  1225. return -1;
  1226. } else {
  1227. if (connection_ap_handshake_send_resolve(conn) < 0)
  1228. return -1;
  1229. }
  1230. return 1;
  1231. }
  1232. /** Try to find a safe live circuit for CONN_TYPE_AP connection conn. If
  1233. * we don't find one: if conn cannot be handled by any known nodes,
  1234. * warn and return -1 (conn needs to die, and is maybe already marked);
  1235. * else launch new circuit (if necessary) and return 0.
  1236. * Otherwise, associate conn with a safe live circuit, do the
  1237. * right next step, and return 1.
  1238. */
  1239. /* XXXX this function should mark for close whenever it returns -1;
  1240. * its callers shouldn't have to worry about that. */
  1241. int
  1242. connection_ap_handshake_attach_circuit(edge_connection_t *conn)
  1243. {
  1244. int retval;
  1245. int conn_age;
  1246. int want_onehop;
  1247. tor_assert(conn);
  1248. tor_assert(conn->_base.state == AP_CONN_STATE_CIRCUIT_WAIT);
  1249. tor_assert(conn->socks_request);
  1250. want_onehop = conn->want_onehop;
  1251. conn_age = (int)(time(NULL) - conn->_base.timestamp_created);
  1252. if (conn_age >= get_options()->SocksTimeout) {
  1253. int severity = (tor_addr_is_null(&conn->_base.addr) && !conn->_base.port) ?
  1254. LOG_INFO : LOG_NOTICE;
  1255. log_fn(severity, LD_APP,
  1256. "Tried for %d seconds to get a connection to %s:%d. Giving up.",
  1257. conn_age, safe_str(conn->socks_request->address),
  1258. conn->socks_request->port);
  1259. return -1;
  1260. }
  1261. if (!connection_edge_is_rendezvous_stream(conn)) { /* we're a general conn */
  1262. origin_circuit_t *circ=NULL;
  1263. if (conn->chosen_exit_name) {
  1264. routerinfo_t *router = router_get_by_nickname(conn->chosen_exit_name, 1);
  1265. int opt = conn->chosen_exit_optional;
  1266. if (!router && !want_onehop) {
  1267. /* We ran into this warning when trying to extend a circuit to a
  1268. * hidden service directory for which we didn't have a router
  1269. * descriptor. See flyspray task 767 for more details. We should
  1270. * keep this in mind when deciding to use BEGIN_DIR cells for other
  1271. * directory requests as well. -KL*/
  1272. log_fn(opt ? LOG_INFO : LOG_WARN, LD_APP,
  1273. "Requested exit point '%s' is not known. %s.",
  1274. conn->chosen_exit_name, opt ? "Trying others" : "Closing");
  1275. if (opt) {
  1276. conn->chosen_exit_optional = 0;
  1277. tor_free(conn->chosen_exit_name);
  1278. return 0;
  1279. }
  1280. return -1;
  1281. }
  1282. if (router && !connection_ap_can_use_exit(conn, router)) {
  1283. log_fn(opt ? LOG_INFO : LOG_WARN, LD_APP,
  1284. "Requested exit point '%s' would refuse request. %s.",
  1285. conn->chosen_exit_name, opt ? "Trying others" : "Closing");
  1286. if (opt) {
  1287. conn->chosen_exit_optional = 0;
  1288. tor_free(conn->chosen_exit_name);
  1289. return 0;
  1290. }
  1291. return -1;
  1292. }
  1293. }
  1294. /* find the circuit that we should use, if there is one. */
  1295. retval = circuit_get_open_circ_or_launch(
  1296. conn, CIRCUIT_PURPOSE_C_GENERAL, &circ);
  1297. if (retval < 1) // XXX021 if we totally fail, this still returns 0 -RD
  1298. return retval;
  1299. log_debug(LD_APP|LD_CIRC,
  1300. "Attaching apconn to circ %d (stream %d sec old).",
  1301. circ->_base.n_circ_id, conn_age);
  1302. /* print the circ's path, so people can figure out which circs are
  1303. * sucking. */
  1304. circuit_log_path(LOG_INFO,LD_APP|LD_CIRC,circ);
  1305. /* We have found a suitable circuit for our conn. Hurray. */
  1306. return connection_ap_handshake_attach_chosen_circuit(conn, circ, NULL);
  1307. } else { /* we're a rendezvous conn */
  1308. origin_circuit_t *rendcirc=NULL, *introcirc=NULL;
  1309. tor_assert(!conn->cpath_layer);
  1310. /* start by finding a rendezvous circuit for us */
  1311. retval = circuit_get_open_circ_or_launch(
  1312. conn, CIRCUIT_PURPOSE_C_REND_JOINED, &rendcirc);
  1313. if (retval < 0) return -1; /* failed */
  1314. if (retval > 0) {
  1315. tor_assert(rendcirc);
  1316. /* one is already established, attach */
  1317. log_info(LD_REND,
  1318. "rend joined circ %d already here. attaching. "
  1319. "(stream %d sec old)",
  1320. rendcirc->_base.n_circ_id, conn_age);
  1321. /* Mark rendezvous circuits as 'newly dirty' every time you use
  1322. * them, since the process of rebuilding a rendezvous circ is so
  1323. * expensive. There is a tradeoff between linkability and
  1324. * feasibility, at this point.
  1325. */
  1326. rendcirc->_base.timestamp_dirty = time(NULL);
  1327. link_apconn_to_circ(conn, rendcirc, NULL);
  1328. if (connection_ap_handshake_send_begin(conn) < 0)
  1329. return 0; /* already marked, let them fade away */
  1330. return 1;
  1331. }
  1332. if (rendcirc && (rendcirc->_base.purpose ==
  1333. CIRCUIT_PURPOSE_C_REND_READY_INTRO_ACKED)) {
  1334. log_info(LD_REND,
  1335. "pending-join circ %d already here, with intro ack. "
  1336. "Stalling. (stream %d sec old)",
  1337. rendcirc->_base.n_circ_id, conn_age);
  1338. return 0;
  1339. }
  1340. /* it's on its way. find an intro circ. */
  1341. retval = circuit_get_open_circ_or_launch(
  1342. conn, CIRCUIT_PURPOSE_C_INTRODUCE_ACK_WAIT, &introcirc);
  1343. if (retval < 0) return -1; /* failed */
  1344. if (retval > 0) {
  1345. /* one has already sent the intro. keep waiting. */
  1346. circuit_t *c = NULL;
  1347. tor_assert(introcirc);
  1348. log_info(LD_REND, "Intro circ %d present and awaiting ack (rend %d). "
  1349. "Stalling. (stream %d sec old)",
  1350. introcirc->_base.n_circ_id,
  1351. rendcirc ? rendcirc->_base.n_circ_id : 0,
  1352. conn_age);
  1353. /* abort parallel intro circs, if any */
  1354. for (c = global_circuitlist; c; c = c->next) {
  1355. if (c->purpose == CIRCUIT_PURPOSE_C_INTRODUCING &&
  1356. !c->marked_for_close && CIRCUIT_IS_ORIGIN(c)) {
  1357. origin_circuit_t *oc = TO_ORIGIN_CIRCUIT(c);
  1358. if (oc->rend_data &&
  1359. !rend_cmp_service_ids(conn->rend_data->onion_address,
  1360. oc->rend_data->onion_address)) {
  1361. log_info(LD_REND|LD_CIRC, "Closing introduction circuit that we "
  1362. "built in parallel.");
  1363. circuit_mark_for_close(c, END_CIRC_REASON_TIMEOUT);
  1364. }
  1365. }
  1366. }
  1367. return 0;
  1368. }
  1369. /* now rendcirc and introcirc are each either undefined or not finished */
  1370. if (rendcirc && introcirc &&
  1371. rendcirc->_base.purpose == CIRCUIT_PURPOSE_C_REND_READY) {
  1372. log_info(LD_REND,
  1373. "ready rend circ %d already here (no intro-ack yet on "
  1374. "intro %d). (stream %d sec old)",
  1375. rendcirc->_base.n_circ_id,
  1376. introcirc->_base.n_circ_id, conn_age);
  1377. tor_assert(introcirc->_base.purpose == CIRCUIT_PURPOSE_C_INTRODUCING);
  1378. if (introcirc->_base.state == CIRCUIT_STATE_OPEN) {
  1379. log_info(LD_REND,"found open intro circ %d (rend %d); sending "
  1380. "introduction. (stream %d sec old)",
  1381. introcirc->_base.n_circ_id, rendcirc->_base.n_circ_id,
  1382. conn_age);
  1383. if (rend_client_send_introduction(introcirc, rendcirc) < 0) {
  1384. return -1;
  1385. }
  1386. rendcirc->_base.timestamp_dirty = time(NULL);
  1387. introcirc->_base.timestamp_dirty = time(NULL);
  1388. assert_circuit_ok(TO_CIRCUIT(rendcirc));
  1389. assert_circuit_ok(TO_CIRCUIT(introcirc));
  1390. return 0;
  1391. }
  1392. }
  1393. log_info(LD_REND, "Intro (%d) and rend (%d) circs are not both ready. "
  1394. "Stalling conn. (%d sec old)",
  1395. introcirc ? introcirc->_base.n_circ_id : 0,
  1396. rendcirc ? rendcirc->_base.n_circ_id : 0, conn_age);
  1397. return 0;
  1398. }
  1399. }