circuituse.c 82 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202
  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-2012, 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 "addressmap.h"
  12. #include "channel.h"
  13. #include "circuitbuild.h"
  14. #include "circuitlist.h"
  15. #include "circuitstats.h"
  16. #include "circuituse.h"
  17. #include "config.h"
  18. #include "connection.h"
  19. #include "connection_edge.h"
  20. #include "control.h"
  21. #include "entrynodes.h"
  22. #include "nodelist.h"
  23. #include "networkstatus.h"
  24. #include "policies.h"
  25. #include "rendclient.h"
  26. #include "rendcommon.h"
  27. #include "rendservice.h"
  28. #include "rephist.h"
  29. #include "router.h"
  30. #include "routerlist.h"
  31. /********* START VARIABLES **********/
  32. extern circuit_t *global_circuitlist; /* from circuitlist.c */
  33. /********* END VARIABLES ************/
  34. static void circuit_expire_old_circuits_clientside(void);
  35. static void circuit_increment_failure_count(void);
  36. /** Return 1 if <b>circ</b> could be returned by circuit_get_best().
  37. * Else return 0.
  38. */
  39. static int
  40. circuit_is_acceptable(const origin_circuit_t *origin_circ,
  41. const entry_connection_t *conn,
  42. int must_be_open, uint8_t purpose,
  43. int need_uptime, int need_internal,
  44. time_t now)
  45. {
  46. const circuit_t *circ = TO_CIRCUIT(origin_circ);
  47. const node_t *exitnode;
  48. cpath_build_state_t *build_state;
  49. tor_assert(circ);
  50. tor_assert(conn);
  51. tor_assert(conn->socks_request);
  52. if (must_be_open && (circ->state != CIRCUIT_STATE_OPEN || !circ->n_chan))
  53. return 0; /* ignore non-open circs */
  54. if (circ->marked_for_close)
  55. return 0;
  56. /* if this circ isn't our purpose, skip. */
  57. if (purpose == CIRCUIT_PURPOSE_C_REND_JOINED && !must_be_open) {
  58. if (circ->purpose != CIRCUIT_PURPOSE_C_ESTABLISH_REND &&
  59. circ->purpose != CIRCUIT_PURPOSE_C_REND_READY &&
  60. circ->purpose != CIRCUIT_PURPOSE_C_REND_READY_INTRO_ACKED &&
  61. circ->purpose != CIRCUIT_PURPOSE_C_REND_JOINED)
  62. return 0;
  63. } else if (purpose == CIRCUIT_PURPOSE_C_INTRODUCE_ACK_WAIT &&
  64. !must_be_open) {
  65. if (circ->purpose != CIRCUIT_PURPOSE_C_INTRODUCING &&
  66. circ->purpose != CIRCUIT_PURPOSE_C_INTRODUCE_ACK_WAIT)
  67. return 0;
  68. } else {
  69. if (purpose != circ->purpose)
  70. return 0;
  71. }
  72. /* If this is a timed-out hidden service circuit, skip it. */
  73. if (origin_circ->hs_circ_has_timed_out) {
  74. return 0;
  75. }
  76. if (purpose == CIRCUIT_PURPOSE_C_GENERAL ||
  77. purpose == CIRCUIT_PURPOSE_C_REND_JOINED)
  78. if (circ->timestamp_dirty &&
  79. circ->timestamp_dirty+get_options()->MaxCircuitDirtiness <= now)
  80. return 0;
  81. /* decide if this circ is suitable for this conn */
  82. /* for rend circs, circ->cpath->prev is not the last router in the
  83. * circuit, it's the magical extra bob hop. so just check the nickname
  84. * of the one we meant to finish at.
  85. */
  86. build_state = origin_circ->build_state;
  87. exitnode = build_state_get_exit_node(build_state);
  88. if (need_uptime && !build_state->need_uptime)
  89. return 0;
  90. if (need_internal != build_state->is_internal)
  91. return 0;
  92. if (purpose == CIRCUIT_PURPOSE_C_GENERAL) {
  93. if (!exitnode && !build_state->onehop_tunnel) {
  94. log_debug(LD_CIRC,"Not considering circuit with unknown router.");
  95. return 0; /* this circuit is screwed and doesn't know it yet,
  96. * or is a rendezvous circuit. */
  97. }
  98. if (build_state->onehop_tunnel) {
  99. if (!conn->want_onehop) {
  100. log_debug(LD_CIRC,"Skipping one-hop circuit.");
  101. return 0;
  102. }
  103. tor_assert(conn->chosen_exit_name);
  104. if (build_state->chosen_exit) {
  105. char digest[DIGEST_LEN];
  106. if (hexdigest_to_digest(conn->chosen_exit_name, digest) < 0)
  107. return 0; /* broken digest, we don't want it */
  108. if (tor_memneq(digest, build_state->chosen_exit->identity_digest,
  109. DIGEST_LEN))
  110. return 0; /* this is a circuit to somewhere else */
  111. if (tor_digest_is_zero(digest)) {
  112. /* we don't know the digest; have to compare addr:port */
  113. tor_addr_t addr;
  114. int r = tor_addr_parse(&addr, conn->socks_request->address);
  115. if (r < 0 ||
  116. !tor_addr_eq(&build_state->chosen_exit->addr, &addr) ||
  117. build_state->chosen_exit->port != conn->socks_request->port)
  118. return 0;
  119. }
  120. }
  121. } else {
  122. if (conn->want_onehop) {
  123. /* don't use three-hop circuits -- that could hurt our anonymity. */
  124. return 0;
  125. }
  126. }
  127. if (exitnode && !connection_ap_can_use_exit(conn, exitnode)) {
  128. /* can't exit from this router */
  129. return 0;
  130. }
  131. } else { /* not general */
  132. const edge_connection_t *edge_conn = ENTRY_TO_EDGE_CONN(conn);
  133. if ((edge_conn->rend_data && !origin_circ->rend_data) ||
  134. (!edge_conn->rend_data && origin_circ->rend_data) ||
  135. (edge_conn->rend_data && origin_circ->rend_data &&
  136. rend_cmp_service_ids(edge_conn->rend_data->onion_address,
  137. origin_circ->rend_data->onion_address))) {
  138. /* this circ is not for this conn */
  139. return 0;
  140. }
  141. }
  142. if (!connection_edge_compatible_with_circuit(conn, origin_circ)) {
  143. /* conn needs to be isolated from other conns that have already used
  144. * origin_circ */
  145. return 0;
  146. }
  147. return 1;
  148. }
  149. /** Return 1 if circuit <b>a</b> is better than circuit <b>b</b> for
  150. * <b>conn</b>, and return 0 otherwise. Used by circuit_get_best.
  151. */
  152. static int
  153. circuit_is_better(const origin_circuit_t *oa, const origin_circuit_t *ob,
  154. const entry_connection_t *conn)
  155. {
  156. const circuit_t *a = TO_CIRCUIT(oa);
  157. const circuit_t *b = TO_CIRCUIT(ob);
  158. const uint8_t purpose = ENTRY_TO_CONN(conn)->purpose;
  159. int a_bits, b_bits;
  160. /* If one of the circuits was allowed to live due to relaxing its timeout,
  161. * it is definitely worse (it's probably a much slower path). */
  162. if (oa->relaxed_timeout && !ob->relaxed_timeout)
  163. return 0; /* ob is better. It's not relaxed. */
  164. if (!oa->relaxed_timeout && ob->relaxed_timeout)
  165. return 1; /* oa is better. It's not relaxed. */
  166. switch (purpose) {
  167. case CIRCUIT_PURPOSE_C_GENERAL:
  168. /* if it's used but less dirty it's best;
  169. * else if it's more recently created it's best
  170. */
  171. if (b->timestamp_dirty) {
  172. if (a->timestamp_dirty &&
  173. a->timestamp_dirty > b->timestamp_dirty)
  174. return 1;
  175. } else {
  176. if (a->timestamp_dirty ||
  177. timercmp(&a->timestamp_began, &b->timestamp_began, >))
  178. return 1;
  179. if (ob->build_state->is_internal)
  180. /* XXX023 what the heck is this internal thing doing here. I
  181. * think we can get rid of it. circuit_is_acceptable() already
  182. * makes sure that is_internal is exactly what we need it to
  183. * be. -RD */
  184. return 1;
  185. }
  186. break;
  187. case CIRCUIT_PURPOSE_C_INTRODUCE_ACK_WAIT:
  188. /* the closer it is to ack_wait the better it is */
  189. if (a->purpose > b->purpose)
  190. return 1;
  191. break;
  192. case CIRCUIT_PURPOSE_C_REND_JOINED:
  193. /* the closer it is to rend_joined the better it is */
  194. if (a->purpose > b->purpose)
  195. return 1;
  196. break;
  197. }
  198. /* XXXX023 Maybe this check should get a higher priority to avoid
  199. * using up circuits too rapidly. */
  200. a_bits = connection_edge_update_circuit_isolation(conn,
  201. (origin_circuit_t*)oa, 1);
  202. b_bits = connection_edge_update_circuit_isolation(conn,
  203. (origin_circuit_t*)ob, 1);
  204. /* if x_bits < 0, then we have not used x for anything; better not to dirty
  205. * a connection if we can help it. */
  206. if (a_bits < 0) {
  207. return 0;
  208. } else if (b_bits < 0) {
  209. return 1;
  210. }
  211. a_bits &= ~ oa->isolation_flags_mixed;
  212. a_bits &= ~ ob->isolation_flags_mixed;
  213. if (n_bits_set_u8(a_bits) < n_bits_set_u8(b_bits)) {
  214. /* The fewer new restrictions we need to make on a circuit for stream
  215. * isolation, the better. */
  216. return 1;
  217. }
  218. return 0;
  219. }
  220. /** Find the best circ that conn can use, preferably one which is
  221. * dirty. Circ must not be too old.
  222. *
  223. * Conn must be defined.
  224. *
  225. * If must_be_open, ignore circs not in CIRCUIT_STATE_OPEN.
  226. *
  227. * circ_purpose specifies what sort of circuit we must have.
  228. * It can be C_GENERAL, C_INTRODUCE_ACK_WAIT, or C_REND_JOINED.
  229. *
  230. * If it's REND_JOINED and must_be_open==0, then return the closest
  231. * rendezvous-purposed circuit that you can find.
  232. *
  233. * If it's INTRODUCE_ACK_WAIT and must_be_open==0, then return the
  234. * closest introduce-purposed circuit that you can find.
  235. */
  236. static origin_circuit_t *
  237. circuit_get_best(const entry_connection_t *conn,
  238. int must_be_open, uint8_t purpose,
  239. int need_uptime, int need_internal)
  240. {
  241. circuit_t *circ;
  242. origin_circuit_t *best=NULL;
  243. struct timeval now;
  244. int intro_going_on_but_too_old = 0;
  245. tor_assert(conn);
  246. tor_assert(purpose == CIRCUIT_PURPOSE_C_GENERAL ||
  247. purpose == CIRCUIT_PURPOSE_C_INTRODUCE_ACK_WAIT ||
  248. purpose == CIRCUIT_PURPOSE_C_REND_JOINED);
  249. tor_gettimeofday(&now);
  250. for (circ=global_circuitlist;circ;circ = circ->next) {
  251. origin_circuit_t *origin_circ;
  252. if (!CIRCUIT_IS_ORIGIN(circ))
  253. continue;
  254. origin_circ = TO_ORIGIN_CIRCUIT(circ);
  255. if (!circuit_is_acceptable(origin_circ,conn,must_be_open,purpose,
  256. need_uptime,need_internal,now.tv_sec))
  257. continue;
  258. if (purpose == CIRCUIT_PURPOSE_C_INTRODUCE_ACK_WAIT &&
  259. !must_be_open && circ->state != CIRCUIT_STATE_OPEN &&
  260. tv_mdiff(&now, &circ->timestamp_began) > circ_times.timeout_ms) {
  261. intro_going_on_but_too_old = 1;
  262. continue;
  263. }
  264. /* now this is an acceptable circ to hand back. but that doesn't
  265. * mean it's the *best* circ to hand back. try to decide.
  266. */
  267. if (!best || circuit_is_better(origin_circ,best,conn))
  268. best = origin_circ;
  269. }
  270. if (!best && intro_going_on_but_too_old)
  271. log_info(LD_REND|LD_CIRC, "There is an intro circuit being created "
  272. "right now, but it has already taken quite a while. Starting "
  273. "one in parallel.");
  274. return best;
  275. }
  276. /** Return the number of not-yet-open general-purpose origin circuits. */
  277. static int
  278. count_pending_general_client_circuits(void)
  279. {
  280. const circuit_t *circ;
  281. int count = 0;
  282. for (circ = global_circuitlist; circ; circ = circ->next) {
  283. if (circ->marked_for_close ||
  284. circ->state == CIRCUIT_STATE_OPEN ||
  285. circ->purpose != CIRCUIT_PURPOSE_C_GENERAL ||
  286. !CIRCUIT_IS_ORIGIN(circ))
  287. continue;
  288. ++count;
  289. }
  290. return count;
  291. }
  292. #if 0
  293. /** Check whether, according to the policies in <b>options</b>, the
  294. * circuit <b>circ</b> makes sense. */
  295. /* XXXX currently only checks Exclude{Exit}Nodes; it should check more.
  296. * Also, it doesn't have the right definition of an exit circuit. Also,
  297. * it's never called. */
  298. int
  299. circuit_conforms_to_options(const origin_circuit_t *circ,
  300. const or_options_t *options)
  301. {
  302. const crypt_path_t *cpath, *cpath_next = NULL;
  303. /* first check if it includes any excluded nodes */
  304. for (cpath = circ->cpath; cpath_next != circ->cpath; cpath = cpath_next) {
  305. cpath_next = cpath->next;
  306. if (routerset_contains_extendinfo(options->ExcludeNodes,
  307. cpath->extend_info))
  308. return 0;
  309. }
  310. /* then consider the final hop */
  311. if (routerset_contains_extendinfo(options->ExcludeExitNodes,
  312. circ->cpath->prev->extend_info))
  313. return 0;
  314. return 1;
  315. }
  316. #endif
  317. /** Close all circuits that start at us, aren't open, and were born
  318. * at least CircuitBuildTimeout seconds ago.
  319. */
  320. void
  321. circuit_expire_building(void)
  322. {
  323. circuit_t *victim, *next_circ = global_circuitlist;
  324. /* circ_times.timeout_ms and circ_times.close_ms are from
  325. * circuit_build_times_get_initial_timeout() if we haven't computed
  326. * custom timeouts yet */
  327. struct timeval general_cutoff, begindir_cutoff, fourhop_cutoff,
  328. cannibalize_cutoff, close_cutoff, extremely_old_cutoff,
  329. hs_extremely_old_cutoff;
  330. const or_options_t *options = get_options();
  331. struct timeval now;
  332. cpath_build_state_t *build_state;
  333. int any_opened_circs = 0;
  334. tor_gettimeofday(&now);
  335. /* Check to see if we have any opened circuits. If we don't,
  336. * we want to be more lenient with timeouts, in case the
  337. * user has relocated and/or changed network connections.
  338. * See bug #3443. */
  339. while (next_circ) {
  340. if (!CIRCUIT_IS_ORIGIN(next_circ) || /* didn't originate here */
  341. next_circ->marked_for_close) { /* don't mess with marked circs */
  342. next_circ = next_circ->next;
  343. continue;
  344. }
  345. if (TO_ORIGIN_CIRCUIT(next_circ)->has_opened &&
  346. next_circ->state == CIRCUIT_STATE_OPEN &&
  347. TO_ORIGIN_CIRCUIT(next_circ)->build_state &&
  348. TO_ORIGIN_CIRCUIT(next_circ)->build_state->desired_path_len
  349. == DEFAULT_ROUTE_LEN) {
  350. any_opened_circs = 1;
  351. break;
  352. }
  353. next_circ = next_circ->next;
  354. }
  355. next_circ = global_circuitlist;
  356. #define SET_CUTOFF(target, msec) do { \
  357. long ms = tor_lround(msec); \
  358. struct timeval diff; \
  359. diff.tv_sec = ms / 1000; \
  360. diff.tv_usec = (int)((ms % 1000) * 1000); \
  361. timersub(&now, &diff, &target); \
  362. } while (0)
  363. SET_CUTOFF(general_cutoff, circ_times.timeout_ms);
  364. SET_CUTOFF(begindir_cutoff, circ_times.timeout_ms);
  365. SET_CUTOFF(fourhop_cutoff, circ_times.timeout_ms * (4/3.0));
  366. SET_CUTOFF(cannibalize_cutoff, circ_times.timeout_ms / 2.0);
  367. SET_CUTOFF(close_cutoff, circ_times.close_ms);
  368. SET_CUTOFF(extremely_old_cutoff, circ_times.close_ms*2 + 1000);
  369. SET_CUTOFF(hs_extremely_old_cutoff,
  370. MAX(circ_times.close_ms*2 + 1000,
  371. options->SocksTimeout * 1000));
  372. while (next_circ) {
  373. struct timeval cutoff;
  374. victim = next_circ;
  375. next_circ = next_circ->next;
  376. if (!CIRCUIT_IS_ORIGIN(victim) || /* didn't originate here */
  377. victim->marked_for_close) /* don't mess with marked circs */
  378. continue;
  379. /* If we haven't yet started the first hop, it means we don't have
  380. * any orconns available, and thus have not started counting time yet
  381. * for this circuit. See circuit_deliver_create_cell() and uses of
  382. * timestamp_began.
  383. *
  384. * Continue to wait in this case. The ORConn should timeout
  385. * independently and kill us then.
  386. */
  387. if (TO_ORIGIN_CIRCUIT(victim)->cpath->state == CPATH_STATE_CLOSED) {
  388. continue;
  389. }
  390. build_state = TO_ORIGIN_CIRCUIT(victim)->build_state;
  391. if (build_state && build_state->onehop_tunnel)
  392. cutoff = begindir_cutoff;
  393. else if (build_state && build_state->desired_path_len == 4
  394. && !TO_ORIGIN_CIRCUIT(victim)->has_opened)
  395. cutoff = fourhop_cutoff;
  396. else if (TO_ORIGIN_CIRCUIT(victim)->has_opened)
  397. cutoff = cannibalize_cutoff;
  398. else if (victim->purpose == CIRCUIT_PURPOSE_C_MEASURE_TIMEOUT)
  399. cutoff = close_cutoff;
  400. else
  401. cutoff = general_cutoff;
  402. if (TO_ORIGIN_CIRCUIT(victim)->hs_circ_has_timed_out)
  403. cutoff = hs_extremely_old_cutoff;
  404. if (timercmp(&victim->timestamp_began, &cutoff, >))
  405. continue; /* it's still young, leave it alone */
  406. if (!any_opened_circs) {
  407. /* It's still young enough that we wouldn't close it, right? */
  408. if (timercmp(&victim->timestamp_began, &close_cutoff, >)) {
  409. if (!TO_ORIGIN_CIRCUIT(victim)->relaxed_timeout) {
  410. int first_hop_succeeded = TO_ORIGIN_CIRCUIT(victim)->cpath->state
  411. == CPATH_STATE_OPEN;
  412. log_info(LD_CIRC,
  413. "No circuits are opened. Relaxing timeout for "
  414. "a circuit with channel state %s. %d guards are live.",
  415. channel_state_to_string(victim->n_chan->state),
  416. num_live_entry_guards(0));
  417. /* We count the timeout here for CBT, because technically this
  418. * was a timeout, and the timeout value needs to reset if we
  419. * see enough of them. Note this means we also need to avoid
  420. * double-counting below, too. */
  421. circuit_build_times_count_timeout(&circ_times, first_hop_succeeded);
  422. TO_ORIGIN_CIRCUIT(victim)->relaxed_timeout = 1;
  423. }
  424. continue;
  425. } else {
  426. static ratelim_t relax_timeout_limit = RATELIM_INIT(3600);
  427. log_fn_ratelim(&relax_timeout_limit, LOG_NOTICE, LD_CIRC,
  428. "No circuits are opened. Relaxed timeout for "
  429. "a circuit with channel state %s to %ldms. "
  430. "However, it appears the circuit has timed out anyway. "
  431. "%d guards are live.",
  432. channel_state_to_string(victim->n_chan->state),
  433. (long)circ_times.close_ms, num_live_entry_guards(0));
  434. }
  435. }
  436. #if 0
  437. /* some debug logs, to help track bugs */
  438. if (victim->purpose >= CIRCUIT_PURPOSE_C_INTRODUCING &&
  439. victim->purpose <= CIRCUIT_PURPOSE_C_REND_READY_INTRO_ACKED) {
  440. if (!victim->timestamp_dirty)
  441. log_fn(LOG_DEBUG,"Considering %sopen purpose %d to %s (circid %d)."
  442. "(clean).",
  443. victim->state == CIRCUIT_STATE_OPEN ? "" : "non",
  444. victim->purpose, victim->build_state->chosen_exit_name,
  445. victim->n_circ_id);
  446. else
  447. log_fn(LOG_DEBUG,"Considering %sopen purpose %d to %s (circid %d). "
  448. "%d secs since dirty.",
  449. victim->state == CIRCUIT_STATE_OPEN ? "" : "non",
  450. victim->purpose, victim->build_state->chosen_exit_name,
  451. victim->n_circ_id,
  452. (int)(now - victim->timestamp_dirty));
  453. }
  454. #endif
  455. /* if circ is !open, or if it's open but purpose is a non-finished
  456. * intro or rend, then mark it for close */
  457. if (victim->state == CIRCUIT_STATE_OPEN) {
  458. switch (victim->purpose) {
  459. default: /* most open circuits can be left alone. */
  460. continue; /* yes, continue inside a switch refers to the nearest
  461. * enclosing loop. C is smart. */
  462. case CIRCUIT_PURPOSE_C_ESTABLISH_REND:
  463. case CIRCUIT_PURPOSE_C_INTRODUCING:
  464. case CIRCUIT_PURPOSE_S_ESTABLISH_INTRO:
  465. break; /* too old, need to die */
  466. case CIRCUIT_PURPOSE_C_REND_READY:
  467. /* it's a rend_ready circ -- has it already picked a query? */
  468. /* c_rend_ready circs measure age since timestamp_dirty,
  469. * because that's set when they switch purposes
  470. */
  471. if (TO_ORIGIN_CIRCUIT(victim)->rend_data ||
  472. victim->timestamp_dirty > cutoff.tv_sec)
  473. continue;
  474. break;
  475. case CIRCUIT_PURPOSE_C_REND_READY_INTRO_ACKED:
  476. case CIRCUIT_PURPOSE_C_INTRODUCE_ACK_WAIT:
  477. /* rend and intro circs become dirty each time they
  478. * make an introduction attempt. so timestamp_dirty
  479. * will reflect the time since the last attempt.
  480. */
  481. if (victim->timestamp_dirty > cutoff.tv_sec)
  482. continue;
  483. break;
  484. }
  485. } else { /* circuit not open, consider recording failure as timeout */
  486. int first_hop_succeeded = TO_ORIGIN_CIRCUIT(victim)->cpath &&
  487. TO_ORIGIN_CIRCUIT(victim)->cpath->state == CPATH_STATE_OPEN;
  488. if (TO_ORIGIN_CIRCUIT(victim)->p_streams != NULL) {
  489. log_warn(LD_BUG, "Circuit %d (purpose %d, %s) has timed out, "
  490. "yet has attached streams!",
  491. TO_ORIGIN_CIRCUIT(victim)->global_identifier,
  492. victim->purpose,
  493. circuit_purpose_to_string(victim->purpose));
  494. tor_fragile_assert();
  495. continue;
  496. }
  497. if (circuit_timeout_want_to_count_circ(TO_ORIGIN_CIRCUIT(victim)) &&
  498. circuit_build_times_enough_to_compute(&circ_times)) {
  499. /* Circuits are allowed to last longer for measurement.
  500. * Switch their purpose and wait. */
  501. if (victim->purpose != CIRCUIT_PURPOSE_C_MEASURE_TIMEOUT) {
  502. control_event_circuit_status(TO_ORIGIN_CIRCUIT(victim),
  503. CIRC_EVENT_FAILED,
  504. END_CIRC_REASON_TIMEOUT);
  505. circuit_change_purpose(victim, CIRCUIT_PURPOSE_C_MEASURE_TIMEOUT);
  506. /* Record this failure to check for too many timeouts
  507. * in a row. This function does not record a time value yet
  508. * (we do that later); it only counts the fact that we did
  509. * have a timeout. We also want to avoid double-counting
  510. * already "relaxed" circuits, which are counted above. */
  511. if (!TO_ORIGIN_CIRCUIT(victim)->relaxed_timeout) {
  512. circuit_build_times_count_timeout(&circ_times,
  513. first_hop_succeeded);
  514. }
  515. continue;
  516. }
  517. /*
  518. * If the circuit build time is much greater than we would have cut
  519. * it off at, we probably had a suspend event along this codepath,
  520. * and we should discard the value.
  521. */
  522. if (timercmp(&victim->timestamp_began, &extremely_old_cutoff, <)) {
  523. log_notice(LD_CIRC,
  524. "Extremely large value for circuit build timeout: %lds. "
  525. "Assuming clock jump. Purpose %d (%s)",
  526. (long)(now.tv_sec - victim->timestamp_began.tv_sec),
  527. victim->purpose,
  528. circuit_purpose_to_string(victim->purpose));
  529. } else if (circuit_build_times_count_close(&circ_times,
  530. first_hop_succeeded,
  531. victim->timestamp_began.tv_sec)) {
  532. circuit_build_times_set_timeout(&circ_times);
  533. }
  534. }
  535. }
  536. /* If this is a hidden service client circuit which is far enough
  537. * along in connecting to its destination, and we haven't already
  538. * flagged it as 'timed out', and the user has not told us to
  539. * close such circs immediately on timeout, flag it as 'timed out'
  540. * so we'll launch another intro or rend circ, but don't mark it
  541. * for close yet.
  542. *
  543. * (Circs flagged as 'timed out' are given a much longer timeout
  544. * period above, so we won't close them in the next call to
  545. * circuit_expire_building.) */
  546. if (!(options->CloseHSClientCircuitsImmediatelyOnTimeout) &&
  547. !(TO_ORIGIN_CIRCUIT(victim)->hs_circ_has_timed_out)) {
  548. switch (victim->purpose) {
  549. case CIRCUIT_PURPOSE_C_REND_READY:
  550. /* We only want to spare a rend circ if it has been specified in
  551. * an INTRODUCE1 cell sent to a hidden service. A circ's
  552. * pending_final_cpath field is non-NULL iff it is a rend circ
  553. * and we have tried to send an INTRODUCE1 cell specifying it.
  554. * Thus, if the pending_final_cpath field *is* NULL, then we
  555. * want to not spare it. */
  556. if (TO_ORIGIN_CIRCUIT(victim)->build_state->pending_final_cpath ==
  557. NULL)
  558. break;
  559. case CIRCUIT_PURPOSE_C_INTRODUCE_ACK_WAIT:
  560. case CIRCUIT_PURPOSE_C_REND_READY_INTRO_ACKED:
  561. /* If we have reached this line, we want to spare the circ for now. */
  562. log_info(LD_CIRC,"Marking circ %d (state %d:%s, purpose %d) "
  563. "as timed-out HS circ",
  564. victim->n_circ_id,
  565. victim->state, circuit_state_to_string(victim->state),
  566. victim->purpose);
  567. TO_ORIGIN_CIRCUIT(victim)->hs_circ_has_timed_out = 1;
  568. continue;
  569. default:
  570. break;
  571. }
  572. }
  573. /* If this is a service-side rendezvous circuit which is far
  574. * enough along in connecting to its destination, consider sparing
  575. * it. */
  576. if (!(options->CloseHSServiceRendCircuitsImmediatelyOnTimeout) &&
  577. !(TO_ORIGIN_CIRCUIT(victim)->hs_circ_has_timed_out) &&
  578. victim->purpose == CIRCUIT_PURPOSE_S_CONNECT_REND) {
  579. log_info(LD_CIRC,"Marking circ %d (state %d:%s, purpose %d) "
  580. "as timed-out HS circ; relaunching rendezvous attempt.",
  581. victim->n_circ_id,
  582. victim->state, circuit_state_to_string(victim->state),
  583. victim->purpose);
  584. TO_ORIGIN_CIRCUIT(victim)->hs_circ_has_timed_out = 1;
  585. rend_service_relaunch_rendezvous(TO_ORIGIN_CIRCUIT(victim));
  586. continue;
  587. }
  588. if (victim->n_chan)
  589. log_info(LD_CIRC,"Abandoning circ %s:%d (state %d:%s, purpose %d)",
  590. channel_get_canonical_remote_descr(victim->n_chan),
  591. victim->n_circ_id,
  592. victim->state, circuit_state_to_string(victim->state),
  593. victim->purpose);
  594. else
  595. log_info(LD_CIRC,"Abandoning circ %d (state %d:%s, purpose %d)",
  596. victim->n_circ_id, victim->state,
  597. circuit_state_to_string(victim->state), victim->purpose);
  598. circuit_log_path(LOG_INFO,LD_CIRC,TO_ORIGIN_CIRCUIT(victim));
  599. if (victim->purpose == CIRCUIT_PURPOSE_C_MEASURE_TIMEOUT)
  600. circuit_mark_for_close(victim, END_CIRC_REASON_MEASUREMENT_EXPIRED);
  601. else
  602. circuit_mark_for_close(victim, END_CIRC_REASON_TIMEOUT);
  603. pathbias_count_timeout(TO_ORIGIN_CIRCUIT(victim));
  604. }
  605. }
  606. /** Remove any elements in <b>needed_ports</b> that are handled by an
  607. * open or in-progress circuit.
  608. */
  609. void
  610. circuit_remove_handled_ports(smartlist_t *needed_ports)
  611. {
  612. int i;
  613. uint16_t *port;
  614. for (i = 0; i < smartlist_len(needed_ports); ++i) {
  615. port = smartlist_get(needed_ports, i);
  616. tor_assert(*port);
  617. if (circuit_stream_is_being_handled(NULL, *port,
  618. MIN_CIRCUITS_HANDLING_STREAM)) {
  619. // log_debug(LD_CIRC,"Port %d is already being handled; removing.", port);
  620. smartlist_del(needed_ports, i--);
  621. tor_free(port);
  622. } else {
  623. log_debug(LD_CIRC,"Port %d is not handled.", *port);
  624. }
  625. }
  626. }
  627. /** Return 1 if at least <b>min</b> general-purpose non-internal circuits
  628. * will have an acceptable exit node for exit stream <b>conn</b> if it
  629. * is defined, else for "*:port".
  630. * Else return 0.
  631. */
  632. int
  633. circuit_stream_is_being_handled(entry_connection_t *conn,
  634. uint16_t port, int min)
  635. {
  636. circuit_t *circ;
  637. const node_t *exitnode;
  638. int num=0;
  639. time_t now = time(NULL);
  640. int need_uptime = smartlist_string_num_isin(get_options()->LongLivedPorts,
  641. conn ? conn->socks_request->port : port);
  642. for (circ=global_circuitlist;circ;circ = circ->next) {
  643. if (CIRCUIT_IS_ORIGIN(circ) &&
  644. !circ->marked_for_close &&
  645. circ->purpose == CIRCUIT_PURPOSE_C_GENERAL &&
  646. (!circ->timestamp_dirty ||
  647. circ->timestamp_dirty + get_options()->MaxCircuitDirtiness > now)) {
  648. cpath_build_state_t *build_state = TO_ORIGIN_CIRCUIT(circ)->build_state;
  649. if (build_state->is_internal || build_state->onehop_tunnel)
  650. continue;
  651. exitnode = build_state_get_exit_node(build_state);
  652. if (exitnode && (!need_uptime || build_state->need_uptime)) {
  653. int ok;
  654. if (conn) {
  655. ok = connection_ap_can_use_exit(conn, exitnode);
  656. } else {
  657. addr_policy_result_t r;
  658. r = compare_tor_addr_to_node_policy(NULL, port, exitnode);
  659. ok = r != ADDR_POLICY_REJECTED && r != ADDR_POLICY_PROBABLY_REJECTED;
  660. }
  661. if (ok) {
  662. if (++num >= min)
  663. return 1;
  664. }
  665. }
  666. }
  667. }
  668. return 0;
  669. }
  670. /** Don't keep more than this many unused open circuits around. */
  671. #define MAX_UNUSED_OPEN_CIRCUITS 14
  672. /** Figure out how many circuits we have open that are clean. Make
  673. * sure it's enough for all the upcoming behaviors we predict we'll have.
  674. * But put an upper bound on the total number of circuits.
  675. */
  676. static void
  677. circuit_predict_and_launch_new(void)
  678. {
  679. circuit_t *circ;
  680. int num=0, num_internal=0, num_uptime_internal=0;
  681. int hidserv_needs_uptime=0, hidserv_needs_capacity=1;
  682. int port_needs_uptime=0, port_needs_capacity=1;
  683. time_t now = time(NULL);
  684. int flags = 0;
  685. /* First, count how many of each type of circuit we have already. */
  686. for (circ=global_circuitlist;circ;circ = circ->next) {
  687. cpath_build_state_t *build_state;
  688. if (!CIRCUIT_IS_ORIGIN(circ))
  689. continue;
  690. if (circ->marked_for_close)
  691. continue; /* don't mess with marked circs */
  692. if (circ->timestamp_dirty)
  693. continue; /* only count clean circs */
  694. if (circ->purpose != CIRCUIT_PURPOSE_C_GENERAL)
  695. continue; /* only pay attention to general-purpose circs */
  696. build_state = TO_ORIGIN_CIRCUIT(circ)->build_state;
  697. if (build_state->onehop_tunnel)
  698. continue;
  699. num++;
  700. if (build_state->is_internal)
  701. num_internal++;
  702. if (build_state->need_uptime && build_state->is_internal)
  703. num_uptime_internal++;
  704. }
  705. /* If that's enough, then stop now. */
  706. if (num >= MAX_UNUSED_OPEN_CIRCUITS)
  707. return; /* we already have many, making more probably will hurt */
  708. /* Second, see if we need any more exit circuits. */
  709. /* check if we know of a port that's been requested recently
  710. * and no circuit is currently available that can handle it. */
  711. if (!circuit_all_predicted_ports_handled(now, &port_needs_uptime,
  712. &port_needs_capacity)) {
  713. if (port_needs_uptime)
  714. flags |= CIRCLAUNCH_NEED_UPTIME;
  715. if (port_needs_capacity)
  716. flags |= CIRCLAUNCH_NEED_CAPACITY;
  717. log_info(LD_CIRC,
  718. "Have %d clean circs (%d internal), need another exit circ.",
  719. num, num_internal);
  720. circuit_launch(CIRCUIT_PURPOSE_C_GENERAL, flags);
  721. return;
  722. }
  723. /* Third, see if we need any more hidden service (server) circuits. */
  724. if (num_rend_services() && num_uptime_internal < 3) {
  725. flags = (CIRCLAUNCH_NEED_CAPACITY | CIRCLAUNCH_NEED_UPTIME |
  726. CIRCLAUNCH_IS_INTERNAL);
  727. log_info(LD_CIRC,
  728. "Have %d clean circs (%d internal), need another internal "
  729. "circ for my hidden service.",
  730. num, num_internal);
  731. circuit_launch(CIRCUIT_PURPOSE_C_GENERAL, flags);
  732. return;
  733. }
  734. /* Fourth, see if we need any more hidden service (client) circuits. */
  735. if (rep_hist_get_predicted_internal(now, &hidserv_needs_uptime,
  736. &hidserv_needs_capacity) &&
  737. ((num_uptime_internal<2 && hidserv_needs_uptime) ||
  738. num_internal<2)) {
  739. if (hidserv_needs_uptime)
  740. flags |= CIRCLAUNCH_NEED_UPTIME;
  741. if (hidserv_needs_capacity)
  742. flags |= CIRCLAUNCH_NEED_CAPACITY;
  743. flags |= CIRCLAUNCH_IS_INTERNAL;
  744. log_info(LD_CIRC,
  745. "Have %d clean circs (%d uptime-internal, %d internal), need"
  746. " another hidden service circ.",
  747. num, num_uptime_internal, num_internal);
  748. circuit_launch(CIRCUIT_PURPOSE_C_GENERAL, flags);
  749. return;
  750. }
  751. /* Finally, check to see if we still need more circuits to learn
  752. * a good build timeout. But if we're close to our max number we
  753. * want, don't do another -- we want to leave a few slots open so
  754. * we can still build circuits preemptively as needed. */
  755. if (num < MAX_UNUSED_OPEN_CIRCUITS-2 &&
  756. get_options()->LearnCircuitBuildTimeout &&
  757. circuit_build_times_needs_circuits_now(&circ_times)) {
  758. flags = CIRCLAUNCH_NEED_CAPACITY;
  759. log_info(LD_CIRC,
  760. "Have %d clean circs need another buildtime test circ.", num);
  761. circuit_launch(CIRCUIT_PURPOSE_C_GENERAL, flags);
  762. return;
  763. }
  764. }
  765. /** Build a new test circuit every 5 minutes */
  766. #define TESTING_CIRCUIT_INTERVAL 300
  767. /** This function is called once a second, if router_have_min_dir_info() is
  768. * true. Its job is to make sure all services we offer have enough circuits
  769. * available. Some services just want enough circuits for current tasks,
  770. * whereas others want a minimum set of idle circuits hanging around.
  771. */
  772. void
  773. circuit_build_needed_circs(time_t now)
  774. {
  775. static time_t time_to_new_circuit = 0;
  776. const or_options_t *options = get_options();
  777. /* launch a new circ for any pending streams that need one */
  778. connection_ap_attach_pending();
  779. /* make sure any hidden services have enough intro points */
  780. rend_services_introduce();
  781. if (time_to_new_circuit < now) {
  782. circuit_reset_failure_count(1);
  783. time_to_new_circuit = now + options->NewCircuitPeriod;
  784. if (proxy_mode(get_options()))
  785. addressmap_clean(now);
  786. circuit_expire_old_circuits_clientside();
  787. #if 0 /* disable for now, until predict-and-launch-new can cull leftovers */
  788. circ = circuit_get_youngest_clean_open(CIRCUIT_PURPOSE_C_GENERAL);
  789. if (get_options()->RunTesting &&
  790. circ &&
  791. circ->timestamp_began.tv_sec + TESTING_CIRCUIT_INTERVAL < now) {
  792. log_fn(LOG_INFO,"Creating a new testing circuit.");
  793. circuit_launch(CIRCUIT_PURPOSE_C_GENERAL, 0);
  794. }
  795. #endif
  796. }
  797. if (!options->DisablePredictedCircuits)
  798. circuit_predict_and_launch_new();
  799. }
  800. /** If the stream <b>conn</b> is a member of any of the linked
  801. * lists of <b>circ</b>, then remove it from the list.
  802. */
  803. void
  804. circuit_detach_stream(circuit_t *circ, edge_connection_t *conn)
  805. {
  806. edge_connection_t *prevconn;
  807. tor_assert(circ);
  808. tor_assert(conn);
  809. if (conn->base_.type == CONN_TYPE_AP) {
  810. entry_connection_t *entry_conn = EDGE_TO_ENTRY_CONN(conn);
  811. entry_conn->may_use_optimistic_data = 0;
  812. }
  813. conn->cpath_layer = NULL; /* don't keep a stale pointer */
  814. conn->on_circuit = NULL;
  815. if (CIRCUIT_IS_ORIGIN(circ)) {
  816. origin_circuit_t *origin_circ = TO_ORIGIN_CIRCUIT(circ);
  817. if (conn == origin_circ->p_streams) {
  818. origin_circ->p_streams = conn->next_stream;
  819. return;
  820. }
  821. for (prevconn = origin_circ->p_streams;
  822. prevconn && prevconn->next_stream && prevconn->next_stream != conn;
  823. prevconn = prevconn->next_stream)
  824. ;
  825. if (prevconn && prevconn->next_stream) {
  826. prevconn->next_stream = conn->next_stream;
  827. return;
  828. }
  829. } else {
  830. or_circuit_t *or_circ = TO_OR_CIRCUIT(circ);
  831. if (conn == or_circ->n_streams) {
  832. or_circ->n_streams = conn->next_stream;
  833. return;
  834. }
  835. if (conn == or_circ->resolving_streams) {
  836. or_circ->resolving_streams = conn->next_stream;
  837. return;
  838. }
  839. for (prevconn = or_circ->n_streams;
  840. prevconn && prevconn->next_stream && prevconn->next_stream != conn;
  841. prevconn = prevconn->next_stream)
  842. ;
  843. if (prevconn && prevconn->next_stream) {
  844. prevconn->next_stream = conn->next_stream;
  845. return;
  846. }
  847. for (prevconn = or_circ->resolving_streams;
  848. prevconn && prevconn->next_stream && prevconn->next_stream != conn;
  849. prevconn = prevconn->next_stream)
  850. ;
  851. if (prevconn && prevconn->next_stream) {
  852. prevconn->next_stream = conn->next_stream;
  853. return;
  854. }
  855. }
  856. log_warn(LD_BUG,"Edge connection not in circuit's list.");
  857. /* Don't give an error here; it's harmless. */
  858. tor_fragile_assert();
  859. }
  860. /** If we haven't yet decided on a good timeout value for circuit
  861. * building, we close idles circuits aggressively so we can get more
  862. * data points. */
  863. #define IDLE_TIMEOUT_WHILE_LEARNING (10*60)
  864. /** Find each circuit that has been unused for too long, or dirty
  865. * for too long and has no streams on it: mark it for close.
  866. */
  867. static void
  868. circuit_expire_old_circuits_clientside(void)
  869. {
  870. circuit_t *circ;
  871. struct timeval cutoff, now;
  872. tor_gettimeofday(&now);
  873. cutoff = now;
  874. if (get_options()->LearnCircuitBuildTimeout &&
  875. circuit_build_times_needs_circuits(&circ_times)) {
  876. /* Circuits should be shorter lived if we need more of them
  877. * for learning a good build timeout */
  878. cutoff.tv_sec -= IDLE_TIMEOUT_WHILE_LEARNING;
  879. } else {
  880. cutoff.tv_sec -= get_options()->CircuitIdleTimeout;
  881. }
  882. for (circ = global_circuitlist; circ; circ = circ->next) {
  883. if (circ->marked_for_close || !CIRCUIT_IS_ORIGIN(circ))
  884. continue;
  885. /* If the circuit has been dirty for too long, and there are no streams
  886. * on it, mark it for close.
  887. */
  888. if (circ->timestamp_dirty &&
  889. circ->timestamp_dirty + get_options()->MaxCircuitDirtiness <
  890. now.tv_sec &&
  891. !TO_ORIGIN_CIRCUIT(circ)->p_streams /* nothing attached */ ) {
  892. log_debug(LD_CIRC, "Closing n_circ_id %d (dirty %ld sec ago, "
  893. "purpose %d)",
  894. circ->n_circ_id, (long)(now.tv_sec - circ->timestamp_dirty),
  895. circ->purpose);
  896. circuit_mark_for_close(circ, END_CIRC_REASON_FINISHED);
  897. } else if (!circ->timestamp_dirty && circ->state == CIRCUIT_STATE_OPEN) {
  898. if (timercmp(&circ->timestamp_began, &cutoff, <)) {
  899. if (circ->purpose == CIRCUIT_PURPOSE_C_GENERAL ||
  900. circ->purpose == CIRCUIT_PURPOSE_C_MEASURE_TIMEOUT ||
  901. circ->purpose == CIRCUIT_PURPOSE_S_ESTABLISH_INTRO ||
  902. circ->purpose == CIRCUIT_PURPOSE_TESTING ||
  903. (circ->purpose >= CIRCUIT_PURPOSE_C_INTRODUCING &&
  904. circ->purpose <= CIRCUIT_PURPOSE_C_REND_READY_INTRO_ACKED) ||
  905. circ->purpose == CIRCUIT_PURPOSE_S_CONNECT_REND) {
  906. log_debug(LD_CIRC,
  907. "Closing circuit that has been unused for %ld msec.",
  908. tv_mdiff(&circ->timestamp_began, &now));
  909. circuit_mark_for_close(circ, END_CIRC_REASON_FINISHED);
  910. } else if (!TO_ORIGIN_CIRCUIT(circ)->is_ancient) {
  911. /* Server-side rend joined circuits can end up really old, because
  912. * they are reused by clients for longer than normal. The client
  913. * controls their lifespan. (They never become dirty, because
  914. * connection_exit_begin_conn() never marks anything as dirty.)
  915. * Similarly, server-side intro circuits last a long time. */
  916. if (circ->purpose != CIRCUIT_PURPOSE_S_REND_JOINED &&
  917. circ->purpose != CIRCUIT_PURPOSE_S_INTRO) {
  918. log_notice(LD_CIRC,
  919. "Ancient non-dirty circuit %d is still around after "
  920. "%ld milliseconds. Purpose: %d (%s)",
  921. TO_ORIGIN_CIRCUIT(circ)->global_identifier,
  922. tv_mdiff(&circ->timestamp_began, &now),
  923. circ->purpose,
  924. circuit_purpose_to_string(circ->purpose));
  925. TO_ORIGIN_CIRCUIT(circ)->is_ancient = 1;
  926. }
  927. }
  928. }
  929. }
  930. }
  931. }
  932. /** How long do we wait before killing circuits with the properties
  933. * described below?
  934. *
  935. * Probably we could choose a number here as low as 5 to 10 seconds,
  936. * since these circs are used for begindir, and a) generally you either
  937. * ask another begindir question right after or you don't for a long time,
  938. * b) clients at least through 0.2.1.x choose from the whole set of
  939. * directory mirrors at each choice, and c) re-establishing a one-hop
  940. * circuit via create-fast is a light operation assuming the TLS conn is
  941. * still there.
  942. *
  943. * I expect "b" to go away one day when we move to using directory
  944. * guards, but I think "a" and "c" are good enough reasons that a low
  945. * number is safe even then.
  946. */
  947. #define IDLE_ONE_HOP_CIRC_TIMEOUT 60
  948. /** Find each non-origin circuit that has been unused for too long,
  949. * has no streams on it, used a create_fast, and ends here: mark it
  950. * for close.
  951. */
  952. void
  953. circuit_expire_old_circuits_serverside(time_t now)
  954. {
  955. circuit_t *circ;
  956. or_circuit_t *or_circ;
  957. time_t cutoff = now - IDLE_ONE_HOP_CIRC_TIMEOUT;
  958. for (circ = global_circuitlist; circ; circ = circ->next) {
  959. if (circ->marked_for_close || CIRCUIT_IS_ORIGIN(circ))
  960. continue;
  961. or_circ = TO_OR_CIRCUIT(circ);
  962. /* If the circuit has been idle for too long, and there are no streams
  963. * on it, and it ends here, and it used a create_fast, mark it for close.
  964. */
  965. if (or_circ->is_first_hop && !circ->n_chan &&
  966. !or_circ->n_streams && !or_circ->resolving_streams &&
  967. or_circ->p_chan &&
  968. channel_when_last_xmit(or_circ->p_chan) <= cutoff) {
  969. log_info(LD_CIRC, "Closing circ_id %d (empty %d secs ago)",
  970. or_circ->p_circ_id,
  971. (int)(now - channel_when_last_xmit(or_circ->p_chan)));
  972. circuit_mark_for_close(circ, END_CIRC_REASON_FINISHED);
  973. }
  974. }
  975. }
  976. /** Number of testing circuits we want open before testing our bandwidth. */
  977. #define NUM_PARALLEL_TESTING_CIRCS 4
  978. /** True iff we've ever had enough testing circuits open to test our
  979. * bandwidth. */
  980. static int have_performed_bandwidth_test = 0;
  981. /** Reset have_performed_bandwidth_test, so we'll start building
  982. * testing circuits again so we can exercise our bandwidth. */
  983. void
  984. reset_bandwidth_test(void)
  985. {
  986. have_performed_bandwidth_test = 0;
  987. }
  988. /** Return 1 if we've already exercised our bandwidth, or if we
  989. * have fewer than NUM_PARALLEL_TESTING_CIRCS testing circuits
  990. * established or on the way. Else return 0.
  991. */
  992. int
  993. circuit_enough_testing_circs(void)
  994. {
  995. circuit_t *circ;
  996. int num = 0;
  997. if (have_performed_bandwidth_test)
  998. return 1;
  999. for (circ = global_circuitlist; circ; circ = circ->next) {
  1000. if (!circ->marked_for_close && CIRCUIT_IS_ORIGIN(circ) &&
  1001. circ->purpose == CIRCUIT_PURPOSE_TESTING &&
  1002. circ->state == CIRCUIT_STATE_OPEN)
  1003. num++;
  1004. }
  1005. return num >= NUM_PARALLEL_TESTING_CIRCS;
  1006. }
  1007. /** A testing circuit has completed. Take whatever stats we want.
  1008. * Noticing reachability is taken care of in onionskin_answer(),
  1009. * so there's no need to record anything here. But if we still want
  1010. * to do the bandwidth test, and we now have enough testing circuits
  1011. * open, do it.
  1012. */
  1013. static void
  1014. circuit_testing_opened(origin_circuit_t *circ)
  1015. {
  1016. if (have_performed_bandwidth_test ||
  1017. !check_whether_orport_reachable()) {
  1018. /* either we've already done everything we want with testing circuits,
  1019. * or this testing circuit became open due to a fluke, e.g. we picked
  1020. * a last hop where we already had the connection open due to an
  1021. * outgoing local circuit. */
  1022. circuit_mark_for_close(TO_CIRCUIT(circ), END_CIRC_AT_ORIGIN);
  1023. } else if (circuit_enough_testing_circs()) {
  1024. router_perform_bandwidth_test(NUM_PARALLEL_TESTING_CIRCS, time(NULL));
  1025. have_performed_bandwidth_test = 1;
  1026. } else
  1027. consider_testing_reachability(1, 0);
  1028. }
  1029. /** A testing circuit has failed to build. Take whatever stats we want. */
  1030. static void
  1031. circuit_testing_failed(origin_circuit_t *circ, int at_last_hop)
  1032. {
  1033. if (server_mode(get_options()) && check_whether_orport_reachable())
  1034. return;
  1035. log_info(LD_GENERAL,
  1036. "Our testing circuit (to see if your ORPort is reachable) "
  1037. "has failed. I'll try again later.");
  1038. /* These aren't used yet. */
  1039. (void)circ;
  1040. (void)at_last_hop;
  1041. }
  1042. /** The circuit <b>circ</b> has just become open. Take the next
  1043. * step: for rendezvous circuits, we pass circ to the appropriate
  1044. * function in rendclient or rendservice. For general circuits, we
  1045. * call connection_ap_attach_pending, which looks for pending streams
  1046. * that could use circ.
  1047. */
  1048. void
  1049. circuit_has_opened(origin_circuit_t *circ)
  1050. {
  1051. control_event_circuit_status(circ, CIRC_EVENT_BUILT, 0);
  1052. /* Cannibalized circuits count as used for path bias.
  1053. * (PURPOSE_GENERAL circs especially, since they are
  1054. * marked dirty and often go unused after preemptive
  1055. * building). */
  1056. // XXX: Cannibalized now use RELAY_EARLY, which is visible
  1057. // to taggers end-to-end! We really need to probe these instead.
  1058. // Don't forget to remove this check once that's done!
  1059. if (circ->has_opened &&
  1060. circ->build_state->desired_path_len > DEFAULT_ROUTE_LEN) {
  1061. circ->path_state = PATH_STATE_USE_SUCCEEDED;
  1062. }
  1063. /* Remember that this circuit has finished building. Now if we start
  1064. * it building again later (e.g. by extending it), we will know not
  1065. * to consider its build time. */
  1066. circ->has_opened = 1;
  1067. switch (TO_CIRCUIT(circ)->purpose) {
  1068. case CIRCUIT_PURPOSE_C_ESTABLISH_REND:
  1069. rend_client_rendcirc_has_opened(circ);
  1070. /* Start building an intro circ if we don't have one yet. */
  1071. connection_ap_attach_pending();
  1072. /* This isn't a call to circuit_try_attaching_streams because a
  1073. * circuit in _C_ESTABLISH_REND state isn't connected to its
  1074. * hidden service yet, thus we can't attach streams to it yet,
  1075. * thus circuit_try_attaching_streams would always clear the
  1076. * circuit's isolation state. circuit_try_attaching_streams is
  1077. * called later, when the rend circ enters _C_REND_JOINED
  1078. * state. */
  1079. break;
  1080. case CIRCUIT_PURPOSE_C_INTRODUCING:
  1081. rend_client_introcirc_has_opened(circ);
  1082. break;
  1083. case CIRCUIT_PURPOSE_C_GENERAL:
  1084. /* Tell any AP connections that have been waiting for a new
  1085. * circuit that one is ready. */
  1086. circuit_try_attaching_streams(circ);
  1087. break;
  1088. case CIRCUIT_PURPOSE_S_ESTABLISH_INTRO:
  1089. /* at Bob, waiting for introductions */
  1090. rend_service_intro_has_opened(circ);
  1091. break;
  1092. case CIRCUIT_PURPOSE_S_CONNECT_REND:
  1093. /* at Bob, connecting to rend point */
  1094. rend_service_rendezvous_has_opened(circ);
  1095. break;
  1096. case CIRCUIT_PURPOSE_TESTING:
  1097. circuit_testing_opened(circ);
  1098. break;
  1099. /* default:
  1100. * This won't happen in normal operation, but might happen if the
  1101. * controller did it. Just let it slide. */
  1102. }
  1103. }
  1104. /** If the stream-isolation state of <b>circ</b> can be cleared, clear
  1105. * it. Return non-zero iff <b>circ</b>'s isolation state was cleared. */
  1106. static int
  1107. circuit_try_clearing_isolation_state(origin_circuit_t *circ)
  1108. {
  1109. if (/* The circuit may have become non-open if it was cannibalized.*/
  1110. circ->base_.state == CIRCUIT_STATE_OPEN &&
  1111. /* If !isolation_values_set, there is nothing to clear. */
  1112. circ->isolation_values_set &&
  1113. /* It's not legal to clear a circuit's isolation info if it's ever had
  1114. * streams attached */
  1115. !circ->isolation_any_streams_attached) {
  1116. /* If we have any isolation information set on this circuit, and
  1117. * we didn't manage to attach any streams to it, then we can
  1118. * and should clear it and try again. */
  1119. circuit_clear_isolation(circ);
  1120. return 1;
  1121. } else {
  1122. return 0;
  1123. }
  1124. }
  1125. /** Called when a circuit becomes ready for streams to be attached to
  1126. * it. */
  1127. void
  1128. circuit_try_attaching_streams(origin_circuit_t *circ)
  1129. {
  1130. /* Attach streams to this circuit if we can. */
  1131. connection_ap_attach_pending();
  1132. /* The call to circuit_try_clearing_isolation_state here will do
  1133. * nothing and return 0 if we didn't attach any streams to circ
  1134. * above. */
  1135. if (circuit_try_clearing_isolation_state(circ)) {
  1136. /* Maybe *now* we can attach some streams to this circuit. */
  1137. connection_ap_attach_pending();
  1138. }
  1139. }
  1140. /** Called whenever a circuit could not be successfully built.
  1141. */
  1142. void
  1143. circuit_build_failed(origin_circuit_t *circ)
  1144. {
  1145. channel_t *n_chan = NULL;
  1146. /* we should examine circ and see if it failed because of
  1147. * the last hop or an earlier hop. then use this info below.
  1148. */
  1149. int failed_at_last_hop = 0;
  1150. /* If the last hop isn't open, and the second-to-last is, we failed
  1151. * at the last hop. */
  1152. if (circ->cpath &&
  1153. circ->cpath->prev->state != CPATH_STATE_OPEN &&
  1154. circ->cpath->prev->prev->state == CPATH_STATE_OPEN) {
  1155. failed_at_last_hop = 1;
  1156. }
  1157. if (circ->cpath &&
  1158. circ->cpath->state != CPATH_STATE_OPEN) {
  1159. /* We failed at the first hop. If there's an OR connection
  1160. * to blame, blame it. Also, avoid this relay for a while, and
  1161. * fail any one-hop directory fetches destined for it. */
  1162. const char *n_chan_id = circ->cpath->extend_info->identity_digest;
  1163. int already_marked = 0;
  1164. if (circ->base_.n_chan) {
  1165. n_chan = circ->base_.n_chan;
  1166. if (n_chan->is_bad_for_new_circs) {
  1167. /* We only want to blame this router when a fresh healthy
  1168. * connection fails. So don't mark this router as newly failed,
  1169. * since maybe this was just an old circuit attempt that's
  1170. * finally timing out now. Also, there's no need to blow away
  1171. * circuits/streams/etc, since the failure of an unhealthy conn
  1172. * doesn't tell us much about whether a healthy conn would
  1173. * succeed. */
  1174. already_marked = 1;
  1175. }
  1176. log_info(LD_OR,
  1177. "Our circuit failed to get a response from the first hop "
  1178. "(%s). I'm going to try to rotate to a better connection.",
  1179. channel_get_canonical_remote_descr(n_chan));
  1180. n_chan->is_bad_for_new_circs = 1;
  1181. } else {
  1182. log_info(LD_OR,
  1183. "Our circuit died before the first hop with no connection");
  1184. }
  1185. if (n_chan_id && !already_marked) {
  1186. entry_guard_register_connect_status(n_chan_id, 0, 1, time(NULL));
  1187. /* if there are any one-hop streams waiting on this circuit, fail
  1188. * them now so they can retry elsewhere. */
  1189. connection_ap_fail_onehop(n_chan_id, circ->build_state);
  1190. }
  1191. }
  1192. switch (circ->base_.purpose) {
  1193. case CIRCUIT_PURPOSE_C_GENERAL:
  1194. /* If we never built the circuit, note it as a failure. */
  1195. circuit_increment_failure_count();
  1196. if (failed_at_last_hop) {
  1197. /* Make sure any streams that demand our last hop as their exit
  1198. * know that it's unlikely to happen. */
  1199. circuit_discard_optional_exit_enclaves(circ->cpath->prev->extend_info);
  1200. }
  1201. break;
  1202. case CIRCUIT_PURPOSE_TESTING:
  1203. circuit_testing_failed(circ, failed_at_last_hop);
  1204. break;
  1205. case CIRCUIT_PURPOSE_S_ESTABLISH_INTRO:
  1206. /* at Bob, waiting for introductions */
  1207. if (circ->base_.state != CIRCUIT_STATE_OPEN) {
  1208. circuit_increment_failure_count();
  1209. }
  1210. /* no need to care here, because bob will rebuild intro
  1211. * points periodically. */
  1212. break;
  1213. case CIRCUIT_PURPOSE_C_INTRODUCING:
  1214. /* at Alice, connecting to intro point */
  1215. /* Don't increment failure count, since Bob may have picked
  1216. * the introduction point maliciously */
  1217. /* Alice will pick a new intro point when this one dies, if
  1218. * the stream in question still cares. No need to act here. */
  1219. break;
  1220. case CIRCUIT_PURPOSE_C_ESTABLISH_REND:
  1221. /* at Alice, waiting for Bob */
  1222. circuit_increment_failure_count();
  1223. /* Alice will pick a new rend point when this one dies, if
  1224. * the stream in question still cares. No need to act here. */
  1225. break;
  1226. case CIRCUIT_PURPOSE_S_CONNECT_REND:
  1227. /* at Bob, connecting to rend point */
  1228. /* Don't increment failure count, since Alice may have picked
  1229. * the rendezvous point maliciously */
  1230. log_info(LD_REND,
  1231. "Couldn't connect to Alice's chosen rend point %s "
  1232. "(%s hop failed).",
  1233. escaped(build_state_get_exit_nickname(circ->build_state)),
  1234. failed_at_last_hop?"last":"non-last");
  1235. rend_service_relaunch_rendezvous(circ);
  1236. break;
  1237. /* default:
  1238. * This won't happen in normal operation, but might happen if the
  1239. * controller did it. Just let it slide. */
  1240. }
  1241. }
  1242. /** Number of consecutive failures so far; should only be touched by
  1243. * circuit_launch_new and circuit_*_failure_count.
  1244. */
  1245. static int n_circuit_failures = 0;
  1246. /** Before the last time we called circuit_reset_failure_count(), were
  1247. * there a lot of failures? */
  1248. static int did_circs_fail_last_period = 0;
  1249. /** Don't retry launching a new circuit if we try this many times with no
  1250. * success. */
  1251. #define MAX_CIRCUIT_FAILURES 5
  1252. /** Launch a new circuit; see circuit_launch_by_extend_info() for
  1253. * details on arguments. */
  1254. origin_circuit_t *
  1255. circuit_launch(uint8_t purpose, int flags)
  1256. {
  1257. return circuit_launch_by_extend_info(purpose, NULL, flags);
  1258. }
  1259. /** Launch a new circuit with purpose <b>purpose</b> and exit node
  1260. * <b>extend_info</b> (or NULL to select a random exit node). If flags
  1261. * contains CIRCLAUNCH_NEED_UPTIME, choose among routers with high uptime. If
  1262. * CIRCLAUNCH_NEED_CAPACITY is set, choose among routers with high bandwidth.
  1263. * If CIRCLAUNCH_IS_INTERNAL is true, the last hop need not be an exit node.
  1264. * If CIRCLAUNCH_ONEHOP_TUNNEL is set, the circuit will have only one hop.
  1265. * Return the newly allocated circuit on success, or NULL on failure. */
  1266. origin_circuit_t *
  1267. circuit_launch_by_extend_info(uint8_t purpose,
  1268. extend_info_t *extend_info,
  1269. int flags)
  1270. {
  1271. origin_circuit_t *circ;
  1272. int onehop_tunnel = (flags & CIRCLAUNCH_ONEHOP_TUNNEL) != 0;
  1273. if (!onehop_tunnel && !router_have_minimum_dir_info()) {
  1274. log_debug(LD_CIRC,"Haven't fetched enough directory info yet; canceling "
  1275. "circuit launch.");
  1276. return NULL;
  1277. }
  1278. if ((extend_info || purpose != CIRCUIT_PURPOSE_C_GENERAL) &&
  1279. purpose != CIRCUIT_PURPOSE_TESTING && !onehop_tunnel) {
  1280. /* see if there are appropriate circs available to cannibalize. */
  1281. /* XXX if we're planning to add a hop, perhaps we want to look for
  1282. * internal circs rather than exit circs? -RD */
  1283. circ = circuit_find_to_cannibalize(purpose, extend_info, flags);
  1284. if (circ) {
  1285. uint8_t old_purpose = circ->base_.purpose;
  1286. struct timeval old_timestamp_began;
  1287. log_info(LD_CIRC,"Cannibalizing circ '%s' for purpose %d (%s)",
  1288. build_state_get_exit_nickname(circ->build_state), purpose,
  1289. circuit_purpose_to_string(purpose));
  1290. if ((purpose == CIRCUIT_PURPOSE_S_CONNECT_REND ||
  1291. purpose == CIRCUIT_PURPOSE_C_INTRODUCING) &&
  1292. circ->path_state == PATH_STATE_BUILD_SUCCEEDED) {
  1293. /* Path bias: Cannibalized rends pre-emptively count as a
  1294. * successfully used circ. We don't wait until the extend,
  1295. * because the rend point could be malicious.
  1296. *
  1297. * Same deal goes for client side introductions. Clients
  1298. * can be manipulated to connect repeatedly to them
  1299. * (especially web clients).
  1300. *
  1301. * If we decide to probe the initial portion of these circs,
  1302. * (up to the adversaries final hop), we need to remove this.
  1303. */
  1304. circ->path_state = PATH_STATE_USE_SUCCEEDED;
  1305. /* This must be called before the purpose change */
  1306. pathbias_check_close(circ, END_CIRC_REASON_FINISHED);
  1307. }
  1308. circuit_change_purpose(TO_CIRCUIT(circ), purpose);
  1309. /* Reset the start date of this circ, else expire_building
  1310. * will see it and think it's been trying to build since it
  1311. * began.
  1312. *
  1313. * Technically, the code should reset this when the
  1314. * create cell is finally sent, but we're close enough
  1315. * here. */
  1316. tor_gettimeofday(&circ->base_.timestamp_began);
  1317. control_event_circuit_cannibalized(circ, old_purpose,
  1318. &old_timestamp_began);
  1319. switch (purpose) {
  1320. case CIRCUIT_PURPOSE_C_ESTABLISH_REND:
  1321. case CIRCUIT_PURPOSE_S_ESTABLISH_INTRO:
  1322. /* it's ready right now */
  1323. break;
  1324. case CIRCUIT_PURPOSE_C_INTRODUCING:
  1325. case CIRCUIT_PURPOSE_S_CONNECT_REND:
  1326. case CIRCUIT_PURPOSE_C_GENERAL:
  1327. /* need to add a new hop */
  1328. tor_assert(extend_info);
  1329. if (circuit_extend_to_new_exit(circ, extend_info) < 0)
  1330. return NULL;
  1331. break;
  1332. default:
  1333. log_warn(LD_BUG,
  1334. "unexpected purpose %d when cannibalizing a circ.",
  1335. purpose);
  1336. tor_fragile_assert();
  1337. return NULL;
  1338. }
  1339. return circ;
  1340. }
  1341. }
  1342. if (did_circs_fail_last_period &&
  1343. n_circuit_failures > MAX_CIRCUIT_FAILURES) {
  1344. /* too many failed circs in a row. don't try. */
  1345. // log_fn(LOG_INFO,"%d failures so far, not trying.",n_circuit_failures);
  1346. return NULL;
  1347. }
  1348. /* try a circ. if it fails, circuit_mark_for_close will increment
  1349. * n_circuit_failures */
  1350. return circuit_establish_circuit(purpose, extend_info, flags);
  1351. }
  1352. /** Record another failure at opening a general circuit. When we have
  1353. * too many, we'll stop trying for the remainder of this minute.
  1354. */
  1355. static void
  1356. circuit_increment_failure_count(void)
  1357. {
  1358. ++n_circuit_failures;
  1359. log_debug(LD_CIRC,"n_circuit_failures now %d.",n_circuit_failures);
  1360. }
  1361. /** Reset the failure count for opening general circuits. This means
  1362. * we will try MAX_CIRCUIT_FAILURES times more (if necessary) before
  1363. * stopping again.
  1364. */
  1365. void
  1366. circuit_reset_failure_count(int timeout)
  1367. {
  1368. if (timeout && n_circuit_failures > MAX_CIRCUIT_FAILURES)
  1369. did_circs_fail_last_period = 1;
  1370. else
  1371. did_circs_fail_last_period = 0;
  1372. n_circuit_failures = 0;
  1373. }
  1374. /** Find an open circ that we're happy to use for <b>conn</b> and return 1. If
  1375. * there isn't one, and there isn't one on the way, launch one and return
  1376. * 0. If it will never work, return -1.
  1377. *
  1378. * Write the found or in-progress or launched circ into *circp.
  1379. */
  1380. static int
  1381. circuit_get_open_circ_or_launch(entry_connection_t *conn,
  1382. uint8_t desired_circuit_purpose,
  1383. origin_circuit_t **circp)
  1384. {
  1385. origin_circuit_t *circ;
  1386. int check_exit_policy;
  1387. int need_uptime, need_internal;
  1388. int want_onehop;
  1389. const or_options_t *options = get_options();
  1390. tor_assert(conn);
  1391. tor_assert(circp);
  1392. tor_assert(ENTRY_TO_CONN(conn)->state == AP_CONN_STATE_CIRCUIT_WAIT);
  1393. check_exit_policy =
  1394. conn->socks_request->command == SOCKS_COMMAND_CONNECT &&
  1395. !conn->use_begindir &&
  1396. !connection_edge_is_rendezvous_stream(ENTRY_TO_EDGE_CONN(conn));
  1397. want_onehop = conn->want_onehop;
  1398. need_uptime = !conn->want_onehop && !conn->use_begindir &&
  1399. smartlist_string_num_isin(options->LongLivedPorts,
  1400. conn->socks_request->port);
  1401. if (desired_circuit_purpose != CIRCUIT_PURPOSE_C_GENERAL)
  1402. need_internal = 1;
  1403. else if (conn->use_begindir || conn->want_onehop)
  1404. need_internal = 1;
  1405. else
  1406. need_internal = 0;
  1407. circ = circuit_get_best(conn, 1, desired_circuit_purpose,
  1408. need_uptime, need_internal);
  1409. if (circ) {
  1410. *circp = circ;
  1411. return 1; /* we're happy */
  1412. }
  1413. if (!want_onehop && !router_have_minimum_dir_info()) {
  1414. if (!connection_get_by_type(CONN_TYPE_DIR)) {
  1415. int severity = LOG_NOTICE;
  1416. /* FFFF if this is a tunneled directory fetch, don't yell
  1417. * as loudly. the user doesn't even know it's happening. */
  1418. if (entry_list_is_constrained(options) &&
  1419. entries_known_but_down(options)) {
  1420. log_fn(severity, LD_APP|LD_DIR,
  1421. "Application request when we haven't used client functionality "
  1422. "lately. Optimistically trying known %s again.",
  1423. options->UseBridges ? "bridges" : "entrynodes");
  1424. entries_retry_all(options);
  1425. } else if (!options->UseBridges || any_bridge_descriptors_known()) {
  1426. log_fn(severity, LD_APP|LD_DIR,
  1427. "Application request when we haven't used client functionality "
  1428. "lately. Optimistically trying directory fetches again.");
  1429. routerlist_retry_directory_downloads(time(NULL));
  1430. }
  1431. }
  1432. /* the stream will be dealt with when router_have_minimum_dir_info becomes
  1433. * 1, or when all directory attempts fail and directory_all_unreachable()
  1434. * kills it.
  1435. */
  1436. return 0;
  1437. }
  1438. /* Do we need to check exit policy? */
  1439. if (check_exit_policy) {
  1440. if (!conn->chosen_exit_name) {
  1441. struct in_addr in;
  1442. tor_addr_t addr, *addrp=NULL;
  1443. if (tor_inet_aton(conn->socks_request->address, &in)) {
  1444. tor_addr_from_in(&addr, &in);
  1445. addrp = &addr;
  1446. }
  1447. if (router_exit_policy_all_nodes_reject(addrp,
  1448. conn->socks_request->port,
  1449. need_uptime)) {
  1450. log_notice(LD_APP,
  1451. "No Tor server allows exit to %s:%d. Rejecting.",
  1452. safe_str_client(conn->socks_request->address),
  1453. conn->socks_request->port);
  1454. return -1;
  1455. }
  1456. } else {
  1457. /* XXXX024 Duplicates checks in connection_ap_handshake_attach_circuit:
  1458. * refactor into a single function? */
  1459. const node_t *node = node_get_by_nickname(conn->chosen_exit_name, 1);
  1460. int opt = conn->chosen_exit_optional;
  1461. if (node && !connection_ap_can_use_exit(conn, node)) {
  1462. log_fn(opt ? LOG_INFO : LOG_WARN, LD_APP,
  1463. "Requested exit point '%s' is excluded or "
  1464. "would refuse request. %s.",
  1465. conn->chosen_exit_name, opt ? "Trying others" : "Closing");
  1466. if (opt) {
  1467. conn->chosen_exit_optional = 0;
  1468. tor_free(conn->chosen_exit_name);
  1469. /* Try again. */
  1470. return circuit_get_open_circ_or_launch(conn,
  1471. desired_circuit_purpose,
  1472. circp);
  1473. }
  1474. return -1;
  1475. }
  1476. }
  1477. }
  1478. /* is one already on the way? */
  1479. circ = circuit_get_best(conn, 0, desired_circuit_purpose,
  1480. need_uptime, need_internal);
  1481. if (circ)
  1482. log_debug(LD_CIRC, "one on the way!");
  1483. if (!circ) {
  1484. extend_info_t *extend_info=NULL;
  1485. uint8_t new_circ_purpose;
  1486. const int n_pending = count_pending_general_client_circuits();
  1487. if (n_pending >= options->MaxClientCircuitsPending) {
  1488. static ratelim_t delay_limit = RATELIM_INIT(10*60);
  1489. char *m;
  1490. if ((m = rate_limit_log(&delay_limit, approx_time()))) {
  1491. log_notice(LD_APP, "We'd like to launch a circuit to handle a "
  1492. "connection, but we already have %d general-purpose client "
  1493. "circuits pending. Waiting until some finish.%s",
  1494. n_pending, m);
  1495. tor_free(m);
  1496. }
  1497. return 0;
  1498. }
  1499. if (desired_circuit_purpose == CIRCUIT_PURPOSE_C_INTRODUCE_ACK_WAIT) {
  1500. /* need to pick an intro point */
  1501. rend_data_t *rend_data = ENTRY_TO_EDGE_CONN(conn)->rend_data;
  1502. tor_assert(rend_data);
  1503. extend_info = rend_client_get_random_intro(rend_data);
  1504. if (!extend_info) {
  1505. log_info(LD_REND,
  1506. "No intro points for '%s': re-fetching service descriptor.",
  1507. safe_str_client(rend_data->onion_address));
  1508. rend_client_refetch_v2_renddesc(rend_data);
  1509. ENTRY_TO_CONN(conn)->state = AP_CONN_STATE_RENDDESC_WAIT;
  1510. return 0;
  1511. }
  1512. log_info(LD_REND,"Chose %s as intro point for '%s'.",
  1513. extend_info_describe(extend_info),
  1514. safe_str_client(rend_data->onion_address));
  1515. }
  1516. /* If we have specified a particular exit node for our
  1517. * connection, then be sure to open a circuit to that exit node.
  1518. */
  1519. if (desired_circuit_purpose == CIRCUIT_PURPOSE_C_GENERAL) {
  1520. if (conn->chosen_exit_name) {
  1521. const node_t *r;
  1522. int opt = conn->chosen_exit_optional;
  1523. r = node_get_by_nickname(conn->chosen_exit_name, 1);
  1524. if (r && node_has_descriptor(r)) {
  1525. /* We might want to connect to an IPv6 bridge for loading
  1526. descriptors so we use the preferred address rather than
  1527. the primary. */
  1528. extend_info = extend_info_from_node(r, conn->want_onehop ? 1 : 0);
  1529. } else {
  1530. log_debug(LD_DIR, "considering %d, %s",
  1531. want_onehop, conn->chosen_exit_name);
  1532. if (want_onehop && conn->chosen_exit_name[0] == '$') {
  1533. /* We're asking for a one-hop circuit to a router that
  1534. * we don't have a routerinfo about. Make up an extend_info. */
  1535. char digest[DIGEST_LEN];
  1536. char *hexdigest = conn->chosen_exit_name+1;
  1537. tor_addr_t addr;
  1538. if (strlen(hexdigest) < HEX_DIGEST_LEN ||
  1539. base16_decode(digest,DIGEST_LEN,hexdigest,HEX_DIGEST_LEN)<0) {
  1540. log_info(LD_DIR, "Broken exit digest on tunnel conn. Closing.");
  1541. return -1;
  1542. }
  1543. if (tor_addr_parse(&addr, conn->socks_request->address) < 0) {
  1544. log_info(LD_DIR, "Broken address %s on tunnel conn. Closing.",
  1545. escaped_safe_str_client(conn->socks_request->address));
  1546. return -1;
  1547. }
  1548. extend_info = extend_info_new(conn->chosen_exit_name+1,
  1549. digest, NULL, &addr,
  1550. conn->socks_request->port);
  1551. } else {
  1552. /* We will need an onion key for the router, and we
  1553. * don't have one. Refuse or relax requirements. */
  1554. log_fn(opt ? LOG_INFO : LOG_WARN, LD_APP,
  1555. "Requested exit point '%s' is not known. %s.",
  1556. conn->chosen_exit_name, opt ? "Trying others" : "Closing");
  1557. if (opt) {
  1558. conn->chosen_exit_optional = 0;
  1559. tor_free(conn->chosen_exit_name);
  1560. /* Try again with no requested exit */
  1561. return circuit_get_open_circ_or_launch(conn,
  1562. desired_circuit_purpose,
  1563. circp);
  1564. }
  1565. return -1;
  1566. }
  1567. }
  1568. }
  1569. }
  1570. if (desired_circuit_purpose == CIRCUIT_PURPOSE_C_REND_JOINED)
  1571. new_circ_purpose = CIRCUIT_PURPOSE_C_ESTABLISH_REND;
  1572. else if (desired_circuit_purpose == CIRCUIT_PURPOSE_C_INTRODUCE_ACK_WAIT)
  1573. new_circ_purpose = CIRCUIT_PURPOSE_C_INTRODUCING;
  1574. else
  1575. new_circ_purpose = desired_circuit_purpose;
  1576. if (options->Tor2webMode &&
  1577. (new_circ_purpose == CIRCUIT_PURPOSE_C_ESTABLISH_REND ||
  1578. new_circ_purpose == CIRCUIT_PURPOSE_C_INTRODUCING)) {
  1579. want_onehop = 1;
  1580. }
  1581. {
  1582. int flags = CIRCLAUNCH_NEED_CAPACITY;
  1583. if (want_onehop) flags |= CIRCLAUNCH_ONEHOP_TUNNEL;
  1584. if (need_uptime) flags |= CIRCLAUNCH_NEED_UPTIME;
  1585. if (need_internal) flags |= CIRCLAUNCH_IS_INTERNAL;
  1586. circ = circuit_launch_by_extend_info(new_circ_purpose, extend_info,
  1587. flags);
  1588. }
  1589. extend_info_free(extend_info);
  1590. if (desired_circuit_purpose == CIRCUIT_PURPOSE_C_GENERAL) {
  1591. /* We just caused a circuit to get built because of this stream.
  1592. * If this stream has caused a _lot_ of circuits to be built, that's
  1593. * a bad sign: we should tell the user. */
  1594. if (conn->num_circuits_launched < NUM_CIRCUITS_LAUNCHED_THRESHOLD &&
  1595. ++conn->num_circuits_launched == NUM_CIRCUITS_LAUNCHED_THRESHOLD)
  1596. log_info(LD_CIRC, "The application request to %s:%d has launched "
  1597. "%d circuits without finding one it likes.",
  1598. escaped_safe_str_client(conn->socks_request->address),
  1599. conn->socks_request->port,
  1600. conn->num_circuits_launched);
  1601. } else {
  1602. /* help predict this next time */
  1603. rep_hist_note_used_internal(time(NULL), need_uptime, 1);
  1604. if (circ) {
  1605. /* write the service_id into circ */
  1606. circ->rend_data = rend_data_dup(ENTRY_TO_EDGE_CONN(conn)->rend_data);
  1607. if (circ->base_.purpose == CIRCUIT_PURPOSE_C_ESTABLISH_REND &&
  1608. circ->base_.state == CIRCUIT_STATE_OPEN)
  1609. rend_client_rendcirc_has_opened(circ);
  1610. }
  1611. }
  1612. } /* endif (!circ) */
  1613. if (circ) {
  1614. /* Mark the circuit with the isolation fields for this connection.
  1615. * When the circuit arrives, we'll clear these flags: this is
  1616. * just some internal bookkeeping to make sure that we have
  1617. * launched enough circuits.
  1618. */
  1619. connection_edge_update_circuit_isolation(conn, circ, 0);
  1620. } else {
  1621. log_info(LD_APP,
  1622. "No safe circuit (purpose %d) ready for edge "
  1623. "connection; delaying.",
  1624. desired_circuit_purpose);
  1625. }
  1626. *circp = circ;
  1627. return 0;
  1628. }
  1629. /** Return true iff <b>crypt_path</b> is one of the crypt_paths for
  1630. * <b>circ</b>. */
  1631. static int
  1632. cpath_is_on_circuit(origin_circuit_t *circ, crypt_path_t *crypt_path)
  1633. {
  1634. crypt_path_t *cpath, *cpath_next = NULL;
  1635. for (cpath = circ->cpath; cpath_next != circ->cpath; cpath = cpath_next) {
  1636. cpath_next = cpath->next;
  1637. if (crypt_path == cpath)
  1638. return 1;
  1639. }
  1640. return 0;
  1641. }
  1642. /** Return true iff client-side optimistic data is supported. */
  1643. static int
  1644. optimistic_data_enabled(void)
  1645. {
  1646. const or_options_t *options = get_options();
  1647. if (options->OptimisticData < 0) {
  1648. /* XXX023 consider having auto default to 1 rather than 0 before
  1649. * the 0.2.3 branch goes stable. See bug 3617. -RD */
  1650. const int32_t enabled =
  1651. networkstatus_get_param(NULL, "UseOptimisticData", 0, 0, 1);
  1652. return (int)enabled;
  1653. }
  1654. return options->OptimisticData;
  1655. }
  1656. /** Attach the AP stream <b>apconn</b> to circ's linked list of
  1657. * p_streams. Also set apconn's cpath_layer to <b>cpath</b>, or to the last
  1658. * hop in circ's cpath if <b>cpath</b> is NULL.
  1659. */
  1660. static void
  1661. link_apconn_to_circ(entry_connection_t *apconn, origin_circuit_t *circ,
  1662. crypt_path_t *cpath)
  1663. {
  1664. const node_t *exitnode;
  1665. /* add it into the linked list of streams on this circuit */
  1666. log_debug(LD_APP|LD_CIRC, "attaching new conn to circ. n_circ_id %d.",
  1667. circ->base_.n_circ_id);
  1668. /* reset it, so we can measure circ timeouts */
  1669. ENTRY_TO_CONN(apconn)->timestamp_lastread = time(NULL);
  1670. ENTRY_TO_EDGE_CONN(apconn)->next_stream = circ->p_streams;
  1671. ENTRY_TO_EDGE_CONN(apconn)->on_circuit = TO_CIRCUIT(circ);
  1672. /* assert_connection_ok(conn, time(NULL)); */
  1673. circ->p_streams = ENTRY_TO_EDGE_CONN(apconn);
  1674. if (connection_edge_is_rendezvous_stream(ENTRY_TO_EDGE_CONN(apconn))) {
  1675. /* We are attaching a stream to a rendezvous circuit. That means
  1676. * that an attempt to connect to a hidden service just
  1677. * succeeded. Tell rendclient.c. */
  1678. rend_client_note_connection_attempt_ended(
  1679. ENTRY_TO_EDGE_CONN(apconn)->rend_data->onion_address);
  1680. }
  1681. if (cpath) { /* we were given one; use it */
  1682. tor_assert(cpath_is_on_circuit(circ, cpath));
  1683. } else {
  1684. /* use the last hop in the circuit */
  1685. tor_assert(circ->cpath);
  1686. tor_assert(circ->cpath->prev);
  1687. tor_assert(circ->cpath->prev->state == CPATH_STATE_OPEN);
  1688. cpath = circ->cpath->prev;
  1689. }
  1690. ENTRY_TO_EDGE_CONN(apconn)->cpath_layer = cpath;
  1691. circ->isolation_any_streams_attached = 1;
  1692. connection_edge_update_circuit_isolation(apconn, circ, 0);
  1693. /* See if we can use optimistic data on this circuit */
  1694. if (cpath->extend_info &&
  1695. (exitnode = node_get_by_id(cpath->extend_info->identity_digest)) &&
  1696. exitnode->rs) {
  1697. /* Okay; we know what exit node this is. */
  1698. if (optimistic_data_enabled() &&
  1699. circ->base_.purpose == CIRCUIT_PURPOSE_C_GENERAL &&
  1700. exitnode->rs->version_supports_optimistic_data)
  1701. apconn->may_use_optimistic_data = 1;
  1702. else
  1703. apconn->may_use_optimistic_data = 0;
  1704. log_info(LD_APP, "Looks like completed circuit to %s %s allow "
  1705. "optimistic data for connection to %s",
  1706. safe_str_client(node_describe(exitnode)),
  1707. apconn->may_use_optimistic_data ? "does" : "doesn't",
  1708. safe_str_client(apconn->socks_request->address));
  1709. }
  1710. }
  1711. /** Return true iff <b>address</b> is matched by one of the entries in
  1712. * TrackHostExits. */
  1713. int
  1714. hostname_in_track_host_exits(const or_options_t *options, const char *address)
  1715. {
  1716. if (!options->TrackHostExits)
  1717. return 0;
  1718. SMARTLIST_FOREACH_BEGIN(options->TrackHostExits, const char *, cp) {
  1719. if (cp[0] == '.') { /* match end */
  1720. if (cp[1] == '\0' ||
  1721. !strcasecmpend(address, cp) ||
  1722. !strcasecmp(address, &cp[1]))
  1723. return 1;
  1724. } else if (strcasecmp(cp, address) == 0) {
  1725. return 1;
  1726. }
  1727. } SMARTLIST_FOREACH_END(cp);
  1728. return 0;
  1729. }
  1730. /** If an exit wasn't explicitly specified for <b>conn</b>, consider saving
  1731. * the exit that we *did* choose for use by future connections to
  1732. * <b>conn</b>'s destination.
  1733. */
  1734. static void
  1735. consider_recording_trackhost(const entry_connection_t *conn,
  1736. const origin_circuit_t *circ)
  1737. {
  1738. const or_options_t *options = get_options();
  1739. char *new_address = NULL;
  1740. char fp[HEX_DIGEST_LEN+1];
  1741. /* Search the addressmap for this conn's destination. */
  1742. /* If he's not in the address map.. */
  1743. if (!options->TrackHostExits ||
  1744. addressmap_have_mapping(conn->socks_request->address,
  1745. options->TrackHostExitsExpire))
  1746. return; /* nothing to track, or already mapped */
  1747. if (!hostname_in_track_host_exits(options, conn->socks_request->address) ||
  1748. !circ->build_state->chosen_exit)
  1749. return;
  1750. /* write down the fingerprint of the chosen exit, not the nickname,
  1751. * because the chosen exit might not be named. */
  1752. base16_encode(fp, sizeof(fp),
  1753. circ->build_state->chosen_exit->identity_digest, DIGEST_LEN);
  1754. /* Add this exit/hostname pair to the addressmap. */
  1755. tor_asprintf(&new_address, "%s.%s.exit",
  1756. conn->socks_request->address, fp);
  1757. addressmap_register(conn->socks_request->address, new_address,
  1758. time(NULL) + options->TrackHostExitsExpire,
  1759. ADDRMAPSRC_TRACKEXIT, 0, 0);
  1760. }
  1761. /** Attempt to attach the connection <b>conn</b> to <b>circ</b>, and send a
  1762. * begin or resolve cell as appropriate. Return values are as for
  1763. * connection_ap_handshake_attach_circuit. The stream will exit from the hop
  1764. * indicated by <b>cpath</b>, or from the last hop in circ's cpath if
  1765. * <b>cpath</b> is NULL. */
  1766. int
  1767. connection_ap_handshake_attach_chosen_circuit(entry_connection_t *conn,
  1768. origin_circuit_t *circ,
  1769. crypt_path_t *cpath)
  1770. {
  1771. connection_t *base_conn = ENTRY_TO_CONN(conn);
  1772. tor_assert(conn);
  1773. tor_assert(base_conn->state == AP_CONN_STATE_CIRCUIT_WAIT ||
  1774. base_conn->state == AP_CONN_STATE_CONTROLLER_WAIT);
  1775. tor_assert(conn->socks_request);
  1776. tor_assert(circ);
  1777. tor_assert(circ->base_.state == CIRCUIT_STATE_OPEN);
  1778. base_conn->state = AP_CONN_STATE_CIRCUIT_WAIT;
  1779. if (!circ->base_.timestamp_dirty)
  1780. circ->base_.timestamp_dirty = time(NULL);
  1781. link_apconn_to_circ(conn, circ, cpath);
  1782. tor_assert(conn->socks_request);
  1783. if (conn->socks_request->command == SOCKS_COMMAND_CONNECT) {
  1784. if (!conn->use_begindir)
  1785. consider_recording_trackhost(conn, circ);
  1786. if (connection_ap_handshake_send_begin(conn) < 0)
  1787. return -1;
  1788. } else {
  1789. if (connection_ap_handshake_send_resolve(conn) < 0)
  1790. return -1;
  1791. }
  1792. return 1;
  1793. }
  1794. /** Try to find a safe live circuit for CONN_TYPE_AP connection conn. If
  1795. * we don't find one: if conn cannot be handled by any known nodes,
  1796. * warn and return -1 (conn needs to die, and is maybe already marked);
  1797. * else launch new circuit (if necessary) and return 0.
  1798. * Otherwise, associate conn with a safe live circuit, do the
  1799. * right next step, and return 1.
  1800. */
  1801. /* XXXX this function should mark for close whenever it returns -1;
  1802. * its callers shouldn't have to worry about that. */
  1803. int
  1804. connection_ap_handshake_attach_circuit(entry_connection_t *conn)
  1805. {
  1806. connection_t *base_conn = ENTRY_TO_CONN(conn);
  1807. int retval;
  1808. int conn_age;
  1809. int want_onehop;
  1810. tor_assert(conn);
  1811. tor_assert(base_conn->state == AP_CONN_STATE_CIRCUIT_WAIT);
  1812. tor_assert(conn->socks_request);
  1813. want_onehop = conn->want_onehop;
  1814. conn_age = (int)(time(NULL) - base_conn->timestamp_created);
  1815. if (conn_age >= get_options()->SocksTimeout) {
  1816. int severity = (tor_addr_is_null(&base_conn->addr) && !base_conn->port) ?
  1817. LOG_INFO : LOG_NOTICE;
  1818. log_fn(severity, LD_APP,
  1819. "Tried for %d seconds to get a connection to %s:%d. Giving up.",
  1820. conn_age, safe_str_client(conn->socks_request->address),
  1821. conn->socks_request->port);
  1822. return -1;
  1823. }
  1824. if (!connection_edge_is_rendezvous_stream(ENTRY_TO_EDGE_CONN(conn))) {
  1825. /* we're a general conn */
  1826. origin_circuit_t *circ=NULL;
  1827. if (conn->chosen_exit_name) {
  1828. const node_t *node = node_get_by_nickname(conn->chosen_exit_name, 1);
  1829. int opt = conn->chosen_exit_optional;
  1830. if (!node && !want_onehop) {
  1831. /* We ran into this warning when trying to extend a circuit to a
  1832. * hidden service directory for which we didn't have a router
  1833. * descriptor. See flyspray task 767 for more details. We should
  1834. * keep this in mind when deciding to use BEGIN_DIR cells for other
  1835. * directory requests as well. -KL*/
  1836. log_fn(opt ? LOG_INFO : LOG_WARN, LD_APP,
  1837. "Requested exit point '%s' is not known. %s.",
  1838. conn->chosen_exit_name, opt ? "Trying others" : "Closing");
  1839. if (opt) {
  1840. conn->chosen_exit_optional = 0;
  1841. tor_free(conn->chosen_exit_name);
  1842. return 0;
  1843. }
  1844. return -1;
  1845. }
  1846. if (node && !connection_ap_can_use_exit(conn, node)) {
  1847. log_fn(opt ? LOG_INFO : LOG_WARN, LD_APP,
  1848. "Requested exit point '%s' is excluded or "
  1849. "would refuse request. %s.",
  1850. conn->chosen_exit_name, opt ? "Trying others" : "Closing");
  1851. if (opt) {
  1852. conn->chosen_exit_optional = 0;
  1853. tor_free(conn->chosen_exit_name);
  1854. return 0;
  1855. }
  1856. return -1;
  1857. }
  1858. }
  1859. /* find the circuit that we should use, if there is one. */
  1860. retval = circuit_get_open_circ_or_launch(
  1861. conn, CIRCUIT_PURPOSE_C_GENERAL, &circ);
  1862. if (retval < 1) // XXX023 if we totally fail, this still returns 0 -RD
  1863. return retval;
  1864. log_debug(LD_APP|LD_CIRC,
  1865. "Attaching apconn to circ %d (stream %d sec old).",
  1866. circ->base_.n_circ_id, conn_age);
  1867. /* print the circ's path, so people can figure out which circs are
  1868. * sucking. */
  1869. circuit_log_path(LOG_INFO,LD_APP|LD_CIRC,circ);
  1870. /* We have found a suitable circuit for our conn. Hurray. */
  1871. return connection_ap_handshake_attach_chosen_circuit(conn, circ, NULL);
  1872. } else { /* we're a rendezvous conn */
  1873. origin_circuit_t *rendcirc=NULL, *introcirc=NULL;
  1874. tor_assert(!ENTRY_TO_EDGE_CONN(conn)->cpath_layer);
  1875. /* start by finding a rendezvous circuit for us */
  1876. retval = circuit_get_open_circ_or_launch(
  1877. conn, CIRCUIT_PURPOSE_C_REND_JOINED, &rendcirc);
  1878. if (retval < 0) return -1; /* failed */
  1879. if (retval > 0) {
  1880. tor_assert(rendcirc);
  1881. /* one is already established, attach */
  1882. log_info(LD_REND,
  1883. "rend joined circ %d already here. attaching. "
  1884. "(stream %d sec old)",
  1885. rendcirc->base_.n_circ_id, conn_age);
  1886. /* Mark rendezvous circuits as 'newly dirty' every time you use
  1887. * them, since the process of rebuilding a rendezvous circ is so
  1888. * expensive. There is a tradeoff between linkability and
  1889. * feasibility, at this point.
  1890. */
  1891. rendcirc->base_.timestamp_dirty = time(NULL);
  1892. link_apconn_to_circ(conn, rendcirc, NULL);
  1893. if (connection_ap_handshake_send_begin(conn) < 0)
  1894. return 0; /* already marked, let them fade away */
  1895. return 1;
  1896. }
  1897. if (rendcirc && (rendcirc->base_.purpose ==
  1898. CIRCUIT_PURPOSE_C_REND_READY_INTRO_ACKED)) {
  1899. log_info(LD_REND,
  1900. "pending-join circ %d already here, with intro ack. "
  1901. "Stalling. (stream %d sec old)",
  1902. rendcirc->base_.n_circ_id, conn_age);
  1903. return 0;
  1904. }
  1905. /* it's on its way. find an intro circ. */
  1906. retval = circuit_get_open_circ_or_launch(
  1907. conn, CIRCUIT_PURPOSE_C_INTRODUCE_ACK_WAIT, &introcirc);
  1908. if (retval < 0) return -1; /* failed */
  1909. if (retval > 0) {
  1910. /* one has already sent the intro. keep waiting. */
  1911. circuit_t *c = NULL;
  1912. tor_assert(introcirc);
  1913. log_info(LD_REND, "Intro circ %d present and awaiting ack (rend %d). "
  1914. "Stalling. (stream %d sec old)",
  1915. introcirc->base_.n_circ_id,
  1916. rendcirc ? rendcirc->base_.n_circ_id : 0,
  1917. conn_age);
  1918. /* abort parallel intro circs, if any */
  1919. for (c = global_circuitlist; c; c = c->next) {
  1920. if (c->purpose == CIRCUIT_PURPOSE_C_INTRODUCING &&
  1921. !c->marked_for_close && CIRCUIT_IS_ORIGIN(c)) {
  1922. origin_circuit_t *oc = TO_ORIGIN_CIRCUIT(c);
  1923. if (oc->rend_data &&
  1924. !rend_cmp_service_ids(
  1925. ENTRY_TO_EDGE_CONN(conn)->rend_data->onion_address,
  1926. oc->rend_data->onion_address)) {
  1927. log_info(LD_REND|LD_CIRC, "Closing introduction circuit that we "
  1928. "built in parallel.");
  1929. circuit_mark_for_close(c, END_CIRC_REASON_TIMEOUT);
  1930. }
  1931. }
  1932. }
  1933. return 0;
  1934. }
  1935. /* now rendcirc and introcirc are each either undefined or not finished */
  1936. if (rendcirc && introcirc &&
  1937. rendcirc->base_.purpose == CIRCUIT_PURPOSE_C_REND_READY) {
  1938. log_info(LD_REND,
  1939. "ready rend circ %d already here (no intro-ack yet on "
  1940. "intro %d). (stream %d sec old)",
  1941. rendcirc->base_.n_circ_id,
  1942. introcirc->base_.n_circ_id, conn_age);
  1943. tor_assert(introcirc->base_.purpose == CIRCUIT_PURPOSE_C_INTRODUCING);
  1944. if (introcirc->base_.state == CIRCUIT_STATE_OPEN) {
  1945. log_info(LD_REND,"found open intro circ %d (rend %d); sending "
  1946. "introduction. (stream %d sec old)",
  1947. introcirc->base_.n_circ_id, rendcirc->base_.n_circ_id,
  1948. conn_age);
  1949. switch (rend_client_send_introduction(introcirc, rendcirc)) {
  1950. case 0: /* success */
  1951. rendcirc->base_.timestamp_dirty = time(NULL);
  1952. introcirc->base_.timestamp_dirty = time(NULL);
  1953. assert_circuit_ok(TO_CIRCUIT(rendcirc));
  1954. assert_circuit_ok(TO_CIRCUIT(introcirc));
  1955. return 0;
  1956. case -1: /* transient error */
  1957. return 0;
  1958. case -2: /* permanent error */
  1959. return -1;
  1960. default: /* oops */
  1961. tor_fragile_assert();
  1962. return -1;
  1963. }
  1964. }
  1965. }
  1966. log_info(LD_REND, "Intro (%d) and rend (%d) circs are not both ready. "
  1967. "Stalling conn. (%d sec old)",
  1968. introcirc ? introcirc->base_.n_circ_id : 0,
  1969. rendcirc ? rendcirc->base_.n_circ_id : 0, conn_age);
  1970. return 0;
  1971. }
  1972. }
  1973. /** Change <b>circ</b>'s purpose to <b>new_purpose</b>. */
  1974. void
  1975. circuit_change_purpose(circuit_t *circ, uint8_t new_purpose)
  1976. {
  1977. uint8_t old_purpose;
  1978. /* Don't allow an OR circ to become an origin circ or vice versa. */
  1979. tor_assert(!!(CIRCUIT_IS_ORIGIN(circ)) ==
  1980. !!(CIRCUIT_PURPOSE_IS_ORIGIN(new_purpose)));
  1981. if (circ->purpose == new_purpose) return;
  1982. if (CIRCUIT_IS_ORIGIN(circ)) {
  1983. char old_purpose_desc[80] = "";
  1984. strncpy(old_purpose_desc, circuit_purpose_to_string(circ->purpose), 80-1);
  1985. old_purpose_desc[80-1] = '\0';
  1986. log_debug(LD_CIRC,
  1987. "changing purpose of origin circ %d "
  1988. "from \"%s\" (%d) to \"%s\" (%d)",
  1989. TO_ORIGIN_CIRCUIT(circ)->global_identifier,
  1990. old_purpose_desc,
  1991. circ->purpose,
  1992. circuit_purpose_to_string(new_purpose),
  1993. new_purpose);
  1994. }
  1995. old_purpose = circ->purpose;
  1996. circ->purpose = new_purpose;
  1997. if (CIRCUIT_IS_ORIGIN(circ)) {
  1998. control_event_circuit_purpose_changed(TO_ORIGIN_CIRCUIT(circ),
  1999. old_purpose);
  2000. }
  2001. }