circuituse.c 61 KB

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