circuituse.c 65 KB

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