circuituse.c 63 KB

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