circuituse.c 65 KB

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