circuituse.c 80 KB

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