circuituse.c 63 KB

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