circuituse.c 61 KB

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