circuituse.c 64 KB

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