circuituse.c 118 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126
  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-2018, 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 the right streams to
  9. * them.
  10. *
  11. * As distinct from circuitlist.c, which manages lookups to find circuits, and
  12. * circuitbuild.c, which handles the logistics of circuit construction, this
  13. * module keeps track of which streams can be attached to which circuits (in
  14. * circuit_get_best()), and attaches streams to circuits (with
  15. * circuit_try_attaching_streams(), connection_ap_handshake_attach_circuit(),
  16. * and connection_ap_handshake_attach_chosen_circuit() ).
  17. *
  18. * This module also makes sure that we are building circuits for all of the
  19. * predicted ports, using circuit_remove_handled_ports(),
  20. * circuit_stream_is_being_handled(), and circuit_build_needed_cirs(). It
  21. * handles launching circuits for specific targets using
  22. * circuit_launch_by_extend_info().
  23. *
  24. * This is also where we handle expiring circuits that have been around for
  25. * too long without actually completing, along with the circuit_build_timeout
  26. * logic in circuitstats.c.
  27. **/
  28. #include "core/or/or.h"
  29. #include "feature/client/addressmap.h"
  30. #include "feature/client/bridges.h"
  31. #include "core/or/channel.h"
  32. #include "feature/client/circpathbias.h"
  33. #include "core/or/circuitbuild.h"
  34. #include "core/or/circuitlist.h"
  35. #include "core/or/circuitstats.h"
  36. #include "core/or/circuituse.h"
  37. #include "app/config/config.h"
  38. #include "core/mainloop/connection.h"
  39. #include "core/or/connection_edge.h"
  40. #include "feature/control/control.h"
  41. #include "feature/dircommon/directory.h"
  42. #include "feature/client/entrynodes.h"
  43. #include "feature/hs/hs_common.h"
  44. #include "feature/hs/hs_client.h"
  45. #include "feature/hs/hs_circuit.h"
  46. #include "feature/hs/hs_ident.h"
  47. #include "feature/hs/hs_stats.h"
  48. #include "feature/nodelist/nodelist.h"
  49. #include "feature/nodelist/networkstatus.h"
  50. #include "core/or/policies.h"
  51. #include "feature/rend/rendclient.h"
  52. #include "feature/rend/rendcommon.h"
  53. #include "feature/rend/rendservice.h"
  54. #include "feature/stats/rephist.h"
  55. #include "feature/relay/router.h"
  56. #include "feature/relay/selftest.h"
  57. #include "feature/nodelist/routerlist.h"
  58. #include "lib/math/fp.h"
  59. #include "lib/time/tvdiff.h"
  60. #include "core/or/cpath_build_state_st.h"
  61. #include "feature/dircommon/dir_connection_st.h"
  62. #include "core/or/entry_connection_st.h"
  63. #include "core/or/extend_info_st.h"
  64. #include "core/or/or_circuit_st.h"
  65. #include "core/or/origin_circuit_st.h"
  66. #include "core/or/socks_request_st.h"
  67. static void circuit_expire_old_circuits_clientside(void);
  68. static void circuit_increment_failure_count(void);
  69. /** Check whether the hidden service destination of the stream at
  70. * <b>edge_conn</b> is the same as the destination of the circuit at
  71. * <b>origin_circ</b>. */
  72. static int
  73. circuit_matches_with_rend_stream(const edge_connection_t *edge_conn,
  74. const origin_circuit_t *origin_circ)
  75. {
  76. /* Check if this is a v2 rendezvous circ/stream */
  77. if ((edge_conn->rend_data && !origin_circ->rend_data) ||
  78. (!edge_conn->rend_data && origin_circ->rend_data) ||
  79. (edge_conn->rend_data && origin_circ->rend_data &&
  80. rend_cmp_service_ids(rend_data_get_address(edge_conn->rend_data),
  81. rend_data_get_address(origin_circ->rend_data)))) {
  82. /* this circ is not for this conn */
  83. return 0;
  84. }
  85. /* Check if this is a v3 rendezvous circ/stream */
  86. if ((edge_conn->hs_ident && !origin_circ->hs_ident) ||
  87. (!edge_conn->hs_ident && origin_circ->hs_ident) ||
  88. (edge_conn->hs_ident && origin_circ->hs_ident &&
  89. !ed25519_pubkey_eq(&edge_conn->hs_ident->identity_pk,
  90. &origin_circ->hs_ident->identity_pk))) {
  91. /* this circ is not for this conn */
  92. return 0;
  93. }
  94. return 1;
  95. }
  96. /** Return 1 if <b>circ</b> could be returned by circuit_get_best().
  97. * Else return 0.
  98. */
  99. static int
  100. circuit_is_acceptable(const origin_circuit_t *origin_circ,
  101. const entry_connection_t *conn,
  102. int must_be_open, uint8_t purpose,
  103. int need_uptime, int need_internal,
  104. time_t now)
  105. {
  106. const circuit_t *circ = TO_CIRCUIT(origin_circ);
  107. const node_t *exitnode;
  108. cpath_build_state_t *build_state;
  109. tor_assert(circ);
  110. tor_assert(conn);
  111. tor_assert(conn->socks_request);
  112. if (must_be_open && (circ->state != CIRCUIT_STATE_OPEN || !circ->n_chan))
  113. return 0; /* ignore non-open circs */
  114. if (circ->marked_for_close)
  115. return 0;
  116. /* if this circ isn't our purpose, skip. */
  117. if (purpose == CIRCUIT_PURPOSE_C_REND_JOINED && !must_be_open) {
  118. if (circ->purpose != CIRCUIT_PURPOSE_C_ESTABLISH_REND &&
  119. circ->purpose != CIRCUIT_PURPOSE_C_REND_READY &&
  120. circ->purpose != CIRCUIT_PURPOSE_C_REND_READY_INTRO_ACKED &&
  121. circ->purpose != CIRCUIT_PURPOSE_C_REND_JOINED)
  122. return 0;
  123. } else if (purpose == CIRCUIT_PURPOSE_C_INTRODUCE_ACK_WAIT &&
  124. !must_be_open) {
  125. if (circ->purpose != CIRCUIT_PURPOSE_C_INTRODUCING &&
  126. circ->purpose != CIRCUIT_PURPOSE_C_INTRODUCE_ACK_WAIT)
  127. return 0;
  128. } else {
  129. if (purpose != circ->purpose)
  130. return 0;
  131. }
  132. /* If this is a timed-out hidden service circuit, skip it. */
  133. if (origin_circ->hs_circ_has_timed_out) {
  134. return 0;
  135. }
  136. if (purpose == CIRCUIT_PURPOSE_C_GENERAL ||
  137. purpose == CIRCUIT_PURPOSE_C_HSDIR_GET ||
  138. purpose == CIRCUIT_PURPOSE_S_HSDIR_POST ||
  139. purpose == CIRCUIT_PURPOSE_HS_VANGUARDS ||
  140. purpose == CIRCUIT_PURPOSE_C_REND_JOINED) {
  141. if (circ->timestamp_dirty &&
  142. circ->timestamp_dirty+get_options()->MaxCircuitDirtiness <= now)
  143. return 0;
  144. }
  145. if (origin_circ->unusable_for_new_conns)
  146. return 0;
  147. /* decide if this circ is suitable for this conn */
  148. /* for rend circs, circ->cpath->prev is not the last router in the
  149. * circuit, it's the magical extra service hop. so just check the nickname
  150. * of the one we meant to finish at.
  151. */
  152. build_state = origin_circ->build_state;
  153. exitnode = build_state_get_exit_node(build_state);
  154. if (need_uptime && !build_state->need_uptime)
  155. return 0;
  156. if (need_internal != build_state->is_internal)
  157. return 0;
  158. if (purpose == CIRCUIT_PURPOSE_C_GENERAL ||
  159. purpose == CIRCUIT_PURPOSE_S_HSDIR_POST ||
  160. purpose == CIRCUIT_PURPOSE_C_HSDIR_GET) {
  161. tor_addr_t addr;
  162. const int family = tor_addr_parse(&addr, conn->socks_request->address);
  163. if (!exitnode && !build_state->onehop_tunnel) {
  164. log_debug(LD_CIRC,"Not considering circuit with unknown router.");
  165. return 0; /* this circuit is screwed and doesn't know it yet,
  166. * or is a rendezvous circuit. */
  167. }
  168. if (build_state->onehop_tunnel) {
  169. if (!conn->want_onehop) {
  170. log_debug(LD_CIRC,"Skipping one-hop circuit.");
  171. return 0;
  172. }
  173. tor_assert(conn->chosen_exit_name);
  174. if (build_state->chosen_exit) {
  175. char digest[DIGEST_LEN];
  176. if (hexdigest_to_digest(conn->chosen_exit_name, digest) < 0)
  177. return 0; /* broken digest, we don't want it */
  178. if (tor_memneq(digest, build_state->chosen_exit->identity_digest,
  179. DIGEST_LEN))
  180. return 0; /* this is a circuit to somewhere else */
  181. if (tor_digest_is_zero(digest)) {
  182. /* we don't know the digest; have to compare addr:port */
  183. if (family < 0 ||
  184. !tor_addr_eq(&build_state->chosen_exit->addr, &addr) ||
  185. build_state->chosen_exit->port != conn->socks_request->port)
  186. return 0;
  187. }
  188. }
  189. } else {
  190. if (conn->want_onehop) {
  191. /* don't use three-hop circuits -- that could hurt our anonymity. */
  192. return 0;
  193. }
  194. }
  195. if (origin_circ->prepend_policy && family != -1) {
  196. int r = compare_tor_addr_to_addr_policy(&addr,
  197. conn->socks_request->port,
  198. origin_circ->prepend_policy);
  199. if (r == ADDR_POLICY_REJECTED)
  200. return 0;
  201. }
  202. if (exitnode && !connection_ap_can_use_exit(conn, exitnode)) {
  203. /* can't exit from this router */
  204. return 0;
  205. }
  206. } else { /* not general: this might be a rend circuit */
  207. const edge_connection_t *edge_conn = ENTRY_TO_EDGE_CONN(conn);
  208. if (!circuit_matches_with_rend_stream(edge_conn, origin_circ)) {
  209. return 0;
  210. }
  211. }
  212. if (!connection_edge_compatible_with_circuit(conn, origin_circ)) {
  213. /* conn needs to be isolated from other conns that have already used
  214. * origin_circ */
  215. return 0;
  216. }
  217. return 1;
  218. }
  219. /** Return 1 if circuit <b>a</b> is better than circuit <b>b</b> for
  220. * <b>conn</b>, and return 0 otherwise. Used by circuit_get_best.
  221. */
  222. static int
  223. circuit_is_better(const origin_circuit_t *oa, const origin_circuit_t *ob,
  224. const entry_connection_t *conn)
  225. {
  226. const circuit_t *a = TO_CIRCUIT(oa);
  227. const circuit_t *b = TO_CIRCUIT(ob);
  228. const uint8_t purpose = ENTRY_TO_CONN(conn)->purpose;
  229. int a_bits, b_bits;
  230. /* If one of the circuits was allowed to live due to relaxing its timeout,
  231. * it is definitely worse (it's probably a much slower path). */
  232. if (oa->relaxed_timeout && !ob->relaxed_timeout)
  233. return 0; /* ob is better. It's not relaxed. */
  234. if (!oa->relaxed_timeout && ob->relaxed_timeout)
  235. return 1; /* oa is better. It's not relaxed. */
  236. switch (purpose) {
  237. case CIRCUIT_PURPOSE_S_HSDIR_POST:
  238. case CIRCUIT_PURPOSE_C_HSDIR_GET:
  239. case CIRCUIT_PURPOSE_C_GENERAL:
  240. /* if it's used but less dirty it's best;
  241. * else if it's more recently created it's best
  242. */
  243. if (b->timestamp_dirty) {
  244. if (a->timestamp_dirty &&
  245. a->timestamp_dirty > b->timestamp_dirty)
  246. return 1;
  247. } else {
  248. if (a->timestamp_dirty ||
  249. timercmp(&a->timestamp_began, &b->timestamp_began, OP_GT))
  250. return 1;
  251. if (ob->build_state->is_internal)
  252. /* XXXX++ what the heck is this internal thing doing here. I
  253. * think we can get rid of it. circuit_is_acceptable() already
  254. * makes sure that is_internal is exactly what we need it to
  255. * be. -RD */
  256. return 1;
  257. }
  258. break;
  259. case CIRCUIT_PURPOSE_C_INTRODUCE_ACK_WAIT:
  260. /* the closer it is to ack_wait the better it is */
  261. if (a->purpose > b->purpose)
  262. return 1;
  263. break;
  264. case CIRCUIT_PURPOSE_C_REND_JOINED:
  265. /* the closer it is to rend_joined the better it is */
  266. if (a->purpose > b->purpose)
  267. return 1;
  268. break;
  269. }
  270. /* XXXX Maybe this check should get a higher priority to avoid
  271. * using up circuits too rapidly. */
  272. a_bits = connection_edge_update_circuit_isolation(conn,
  273. (origin_circuit_t*)oa, 1);
  274. b_bits = connection_edge_update_circuit_isolation(conn,
  275. (origin_circuit_t*)ob, 1);
  276. /* if x_bits < 0, then we have not used x for anything; better not to dirty
  277. * a connection if we can help it. */
  278. if (a_bits < 0) {
  279. return 0;
  280. } else if (b_bits < 0) {
  281. return 1;
  282. }
  283. a_bits &= ~ oa->isolation_flags_mixed;
  284. a_bits &= ~ ob->isolation_flags_mixed;
  285. if (n_bits_set_u8(a_bits) < n_bits_set_u8(b_bits)) {
  286. /* The fewer new restrictions we need to make on a circuit for stream
  287. * isolation, the better. */
  288. return 1;
  289. }
  290. return 0;
  291. }
  292. /** Find the best circ that conn can use, preferably one which is
  293. * dirty. Circ must not be too old.
  294. *
  295. * Conn must be defined.
  296. *
  297. * If must_be_open, ignore circs not in CIRCUIT_STATE_OPEN.
  298. *
  299. * circ_purpose specifies what sort of circuit we must have.
  300. * It can be C_GENERAL, C_INTRODUCE_ACK_WAIT, or C_REND_JOINED.
  301. *
  302. * If it's REND_JOINED and must_be_open==0, then return the closest
  303. * rendezvous-purposed circuit that you can find.
  304. *
  305. * If it's INTRODUCE_ACK_WAIT and must_be_open==0, then return the
  306. * closest introduce-purposed circuit that you can find.
  307. */
  308. static origin_circuit_t *
  309. circuit_get_best(const entry_connection_t *conn,
  310. int must_be_open, uint8_t purpose,
  311. int need_uptime, int need_internal)
  312. {
  313. origin_circuit_t *best=NULL;
  314. struct timeval now;
  315. int intro_going_on_but_too_old = 0;
  316. tor_assert(conn);
  317. tor_assert(purpose == CIRCUIT_PURPOSE_C_GENERAL ||
  318. purpose == CIRCUIT_PURPOSE_HS_VANGUARDS ||
  319. purpose == CIRCUIT_PURPOSE_C_HSDIR_GET ||
  320. purpose == CIRCUIT_PURPOSE_S_HSDIR_POST ||
  321. purpose == CIRCUIT_PURPOSE_C_INTRODUCE_ACK_WAIT ||
  322. purpose == CIRCUIT_PURPOSE_C_REND_JOINED);
  323. tor_gettimeofday(&now);
  324. SMARTLIST_FOREACH_BEGIN(circuit_get_global_list(), circuit_t *, circ) {
  325. origin_circuit_t *origin_circ;
  326. if (!CIRCUIT_IS_ORIGIN(circ))
  327. continue;
  328. origin_circ = TO_ORIGIN_CIRCUIT(circ);
  329. /* Log an info message if we're going to launch a new intro circ in
  330. * parallel */
  331. if (purpose == CIRCUIT_PURPOSE_C_INTRODUCE_ACK_WAIT &&
  332. !must_be_open && origin_circ->hs_circ_has_timed_out &&
  333. !circ->marked_for_close) {
  334. intro_going_on_but_too_old = 1;
  335. continue;
  336. }
  337. if (!circuit_is_acceptable(origin_circ,conn,must_be_open,purpose,
  338. need_uptime,need_internal, (time_t)now.tv_sec))
  339. continue;
  340. /* now this is an acceptable circ to hand back. but that doesn't
  341. * mean it's the *best* circ to hand back. try to decide.
  342. */
  343. if (!best || circuit_is_better(origin_circ,best,conn))
  344. best = origin_circ;
  345. }
  346. SMARTLIST_FOREACH_END(circ);
  347. if (!best && intro_going_on_but_too_old)
  348. log_info(LD_REND|LD_CIRC, "There is an intro circuit being created "
  349. "right now, but it has already taken quite a while. Starting "
  350. "one in parallel.");
  351. return best;
  352. }
  353. /** Return the number of not-yet-open general-purpose origin circuits. */
  354. static int
  355. count_pending_general_client_circuits(void)
  356. {
  357. int count = 0;
  358. SMARTLIST_FOREACH_BEGIN(circuit_get_global_list(), circuit_t *, circ) {
  359. if (circ->marked_for_close ||
  360. circ->state == CIRCUIT_STATE_OPEN ||
  361. !CIRCUIT_PURPOSE_COUNTS_TOWARDS_MAXPENDING(circ->purpose) ||
  362. !CIRCUIT_IS_ORIGIN(circ))
  363. continue;
  364. ++count;
  365. }
  366. SMARTLIST_FOREACH_END(circ);
  367. return count;
  368. }
  369. #if 0
  370. /** Check whether, according to the policies in <b>options</b>, the
  371. * circuit <b>circ</b> makes sense. */
  372. /* XXXX currently only checks Exclude{Exit}Nodes; it should check more.
  373. * Also, it doesn't have the right definition of an exit circuit. Also,
  374. * it's never called. */
  375. int
  376. circuit_conforms_to_options(const origin_circuit_t *circ,
  377. const or_options_t *options)
  378. {
  379. const crypt_path_t *cpath, *cpath_next = NULL;
  380. /* first check if it includes any excluded nodes */
  381. for (cpath = circ->cpath; cpath_next != circ->cpath; cpath = cpath_next) {
  382. cpath_next = cpath->next;
  383. if (routerset_contains_extendinfo(options->ExcludeNodes,
  384. cpath->extend_info))
  385. return 0;
  386. }
  387. /* then consider the final hop */
  388. if (routerset_contains_extendinfo(options->ExcludeExitNodes,
  389. circ->cpath->prev->extend_info))
  390. return 0;
  391. return 1;
  392. }
  393. #endif /* 0 */
  394. /**
  395. * Close all circuits that start at us, aren't open, and were born
  396. * at least CircuitBuildTimeout seconds ago.
  397. *
  398. * TODO: This function is now partially redundant to
  399. * circuit_build_times_handle_completed_hop(), but that function only
  400. * covers circuits up to and including 3 hops that are still actually
  401. * completing hops. However, circuit_expire_building() also handles longer
  402. * circuits, as well as circuits that are completely stalled.
  403. * In the future (after prop247/other path selection revamping), we probably
  404. * want to eliminate this rats nest in favor of a simpler approach.
  405. */
  406. void
  407. circuit_expire_building(void)
  408. {
  409. /* circ_times.timeout_ms and circ_times.close_ms are from
  410. * circuit_build_times_get_initial_timeout() if we haven't computed
  411. * custom timeouts yet */
  412. struct timeval general_cutoff, begindir_cutoff, fourhop_cutoff,
  413. close_cutoff, extremely_old_cutoff, hs_extremely_old_cutoff,
  414. cannibalized_cutoff, c_intro_cutoff, s_intro_cutoff, stream_cutoff;
  415. const or_options_t *options = get_options();
  416. struct timeval now;
  417. cpath_build_state_t *build_state;
  418. int any_opened_circs = 0;
  419. tor_gettimeofday(&now);
  420. /* Check to see if we have any opened circuits. If we don't,
  421. * we want to be more lenient with timeouts, in case the
  422. * user has relocated and/or changed network connections.
  423. * See bug #3443. */
  424. any_opened_circs = circuit_any_opened_circuits();
  425. #define SET_CUTOFF(target, msec) do { \
  426. long ms = tor_lround(msec); \
  427. struct timeval diff; \
  428. diff.tv_sec = ms / 1000; \
  429. diff.tv_usec = (int)((ms % 1000) * 1000); \
  430. timersub(&now, &diff, &target); \
  431. } while (0)
  432. /**
  433. * Because circuit build timeout is calculated only based on 3 hop
  434. * general purpose circuit construction, we need to scale the timeout
  435. * to make it properly apply to longer circuits, and circuits of
  436. * certain usage types. The following diagram illustrates how we
  437. * derive the scaling below. In short, we calculate the number
  438. * of times our telescoping-based circuit construction causes cells
  439. * to traverse each link for the circuit purpose types in question,
  440. * and then assume each link is equivalent.
  441. *
  442. * OP --a--> A --b--> B --c--> C
  443. * OP --a--> A --b--> B --c--> C --d--> D
  444. *
  445. * Let h = a = b = c = d
  446. *
  447. * Three hops (general_cutoff)
  448. * RTTs = 3a + 2b + c
  449. * RTTs = 6h
  450. * Cannibalized:
  451. * RTTs = a+b+c+d
  452. * RTTs = 4h
  453. * Four hops:
  454. * RTTs = 4a + 3b + 2c + d
  455. * RTTs = 10h
  456. * Client INTRODUCE1+ACK: // XXX: correct?
  457. * RTTs = 5a + 4b + 3c + 2d
  458. * RTTs = 14h
  459. * Server intro:
  460. * RTTs = 4a + 3b + 2c
  461. * RTTs = 9h
  462. */
  463. SET_CUTOFF(general_cutoff, get_circuit_build_timeout_ms());
  464. SET_CUTOFF(begindir_cutoff, get_circuit_build_timeout_ms());
  465. // TODO: We should probably use route_len_for_purpose() here instead,
  466. // except that does not count the extra round trip for things like server
  467. // intros and rends.
  468. /* > 3hop circs seem to have a 1.0 second delay on their cannibalized
  469. * 4th hop. */
  470. SET_CUTOFF(fourhop_cutoff, get_circuit_build_timeout_ms() * (10/6.0) + 1000);
  471. /* CIRCUIT_PURPOSE_C_ESTABLISH_REND behaves more like a RELAY cell.
  472. * Use the stream cutoff (more or less). */
  473. SET_CUTOFF(stream_cutoff, MAX(options->CircuitStreamTimeout,15)*1000 + 1000);
  474. /* Be lenient with cannibalized circs. They already survived the official
  475. * CBT, and they're usually not performance-critical. */
  476. SET_CUTOFF(cannibalized_cutoff,
  477. MAX(get_circuit_build_close_time_ms()*(4/6.0),
  478. options->CircuitStreamTimeout * 1000) + 1000);
  479. /* Intro circs have an extra round trip (and are also 4 hops long) */
  480. SET_CUTOFF(c_intro_cutoff, get_circuit_build_timeout_ms() * (14/6.0) + 1000);
  481. /* Server intro circs have an extra round trip */
  482. SET_CUTOFF(s_intro_cutoff, get_circuit_build_timeout_ms() * (9/6.0) + 1000);
  483. SET_CUTOFF(close_cutoff, get_circuit_build_close_time_ms());
  484. SET_CUTOFF(extremely_old_cutoff, get_circuit_build_close_time_ms()*2 + 1000);
  485. SET_CUTOFF(hs_extremely_old_cutoff,
  486. MAX(get_circuit_build_close_time_ms()*2 + 1000,
  487. options->SocksTimeout * 1000));
  488. SMARTLIST_FOREACH_BEGIN(circuit_get_global_list(), circuit_t *,victim) {
  489. struct timeval cutoff;
  490. if (!CIRCUIT_IS_ORIGIN(victim) || /* didn't originate here */
  491. victim->marked_for_close) /* don't mess with marked circs */
  492. continue;
  493. /* If we haven't yet started the first hop, it means we don't have
  494. * any orconns available, and thus have not started counting time yet
  495. * for this circuit. See circuit_deliver_create_cell() and uses of
  496. * timestamp_began.
  497. *
  498. * Continue to wait in this case. The ORConn should timeout
  499. * independently and kill us then.
  500. */
  501. if (TO_ORIGIN_CIRCUIT(victim)->cpath->state == CPATH_STATE_CLOSED) {
  502. continue;
  503. }
  504. build_state = TO_ORIGIN_CIRCUIT(victim)->build_state;
  505. if (build_state && build_state->onehop_tunnel)
  506. cutoff = begindir_cutoff;
  507. else if (victim->purpose == CIRCUIT_PURPOSE_C_MEASURE_TIMEOUT)
  508. cutoff = close_cutoff;
  509. else if (victim->purpose == CIRCUIT_PURPOSE_C_INTRODUCE_ACK_WAIT)
  510. cutoff = c_intro_cutoff;
  511. else if (victim->purpose == CIRCUIT_PURPOSE_S_ESTABLISH_INTRO)
  512. cutoff = s_intro_cutoff;
  513. else if (victim->purpose == CIRCUIT_PURPOSE_C_ESTABLISH_REND)
  514. cutoff = stream_cutoff;
  515. else if (victim->purpose == CIRCUIT_PURPOSE_PATH_BIAS_TESTING)
  516. cutoff = close_cutoff;
  517. else if (TO_ORIGIN_CIRCUIT(victim)->has_opened &&
  518. victim->state != CIRCUIT_STATE_OPEN)
  519. cutoff = cannibalized_cutoff;
  520. else if (build_state && build_state->desired_path_len >= 4)
  521. cutoff = fourhop_cutoff;
  522. else
  523. cutoff = general_cutoff;
  524. if (TO_ORIGIN_CIRCUIT(victim)->hs_circ_has_timed_out)
  525. cutoff = hs_extremely_old_cutoff;
  526. if (timercmp(&victim->timestamp_began, &cutoff, OP_GT))
  527. continue; /* it's still young, leave it alone */
  528. /* We need to double-check the opened state here because
  529. * we don't want to consider opened 1-hop dircon circuits for
  530. * deciding when to relax the timeout, but we *do* want to relax
  531. * those circuits too if nothing else is opened *and* they still
  532. * aren't either. */
  533. if (!any_opened_circs && victim->state != CIRCUIT_STATE_OPEN) {
  534. /* It's still young enough that we wouldn't close it, right? */
  535. if (timercmp(&victim->timestamp_began, &close_cutoff, OP_GT)) {
  536. if (!TO_ORIGIN_CIRCUIT(victim)->relaxed_timeout) {
  537. int first_hop_succeeded = TO_ORIGIN_CIRCUIT(victim)->cpath->state
  538. == CPATH_STATE_OPEN;
  539. log_info(LD_CIRC,
  540. "No circuits are opened. Relaxing timeout for circuit %d "
  541. "(a %s %d-hop circuit in state %s with channel state %s).",
  542. TO_ORIGIN_CIRCUIT(victim)->global_identifier,
  543. circuit_purpose_to_string(victim->purpose),
  544. TO_ORIGIN_CIRCUIT(victim)->build_state ?
  545. TO_ORIGIN_CIRCUIT(victim)->build_state->desired_path_len :
  546. -1,
  547. circuit_state_to_string(victim->state),
  548. victim->n_chan ?
  549. channel_state_to_string(victim->n_chan->state) : "none");
  550. /* We count the timeout here for CBT, because technically this
  551. * was a timeout, and the timeout value needs to reset if we
  552. * see enough of them. Note this means we also need to avoid
  553. * double-counting below, too. */
  554. circuit_build_times_count_timeout(get_circuit_build_times_mutable(),
  555. first_hop_succeeded);
  556. TO_ORIGIN_CIRCUIT(victim)->relaxed_timeout = 1;
  557. }
  558. continue;
  559. } else {
  560. static ratelim_t relax_timeout_limit = RATELIM_INIT(3600);
  561. const double build_close_ms = get_circuit_build_close_time_ms();
  562. log_fn_ratelim(&relax_timeout_limit, LOG_NOTICE, LD_CIRC,
  563. "No circuits are opened. Relaxed timeout for circuit %d "
  564. "(a %s %d-hop circuit in state %s with channel state %s) to "
  565. "%ldms. However, it appears the circuit has timed out "
  566. "anyway.",
  567. TO_ORIGIN_CIRCUIT(victim)->global_identifier,
  568. circuit_purpose_to_string(victim->purpose),
  569. TO_ORIGIN_CIRCUIT(victim)->build_state ?
  570. TO_ORIGIN_CIRCUIT(victim)->build_state->desired_path_len :
  571. -1,
  572. circuit_state_to_string(victim->state),
  573. victim->n_chan ?
  574. channel_state_to_string(victim->n_chan->state) : "none",
  575. (long)build_close_ms);
  576. }
  577. }
  578. #if 0
  579. /* some debug logs, to help track bugs */
  580. if (victim->purpose >= CIRCUIT_PURPOSE_C_INTRODUCING &&
  581. victim->purpose <= CIRCUIT_PURPOSE_C_REND_READY_INTRO_ACKED) {
  582. if (!victim->timestamp_dirty)
  583. log_fn(LOG_DEBUG,"Considering %sopen purpose %d to %s (circid %d)."
  584. "(clean).",
  585. victim->state == CIRCUIT_STATE_OPEN ? "" : "non",
  586. victim->purpose, victim->build_state->chosen_exit_name,
  587. victim->n_circ_id);
  588. else
  589. log_fn(LOG_DEBUG,"Considering %sopen purpose %d to %s (circid %d). "
  590. "%d secs since dirty.",
  591. victim->state == CIRCUIT_STATE_OPEN ? "" : "non",
  592. victim->purpose, victim->build_state->chosen_exit_name,
  593. victim->n_circ_id,
  594. (int)(now - victim->timestamp_dirty));
  595. }
  596. #endif /* 0 */
  597. /* if circ is !open, or if it's open but purpose is a non-finished
  598. * intro or rend, then mark it for close */
  599. if (victim->state == CIRCUIT_STATE_OPEN) {
  600. switch (victim->purpose) {
  601. default: /* most open circuits can be left alone. */
  602. continue; /* yes, continue inside a switch refers to the nearest
  603. * enclosing loop. C is smart. */
  604. case CIRCUIT_PURPOSE_S_ESTABLISH_INTRO:
  605. break; /* too old, need to die */
  606. case CIRCUIT_PURPOSE_C_REND_READY:
  607. /* it's a rend_ready circ -- has it already picked a query? */
  608. /* c_rend_ready circs measure age since timestamp_dirty,
  609. * because that's set when they switch purposes
  610. */
  611. if (TO_ORIGIN_CIRCUIT(victim)->rend_data ||
  612. TO_ORIGIN_CIRCUIT(victim)->hs_ident ||
  613. victim->timestamp_dirty > cutoff.tv_sec)
  614. continue;
  615. break;
  616. case CIRCUIT_PURPOSE_PATH_BIAS_TESTING:
  617. /* Open path bias testing circuits are given a long
  618. * time to complete the test, but not forever */
  619. TO_ORIGIN_CIRCUIT(victim)->path_state = PATH_STATE_USE_FAILED;
  620. break;
  621. case CIRCUIT_PURPOSE_C_INTRODUCING:
  622. /* That purpose means that the intro point circuit has been opened
  623. * successfully but the INTRODUCE1 cell hasn't been sent yet because
  624. * the client is waiting for the rendezvous point circuit to open.
  625. * Keep this circuit open while waiting for the rendezvous circuit.
  626. * We let the circuit idle timeout take care of cleaning this
  627. * circuit if it never used. */
  628. continue;
  629. case CIRCUIT_PURPOSE_C_ESTABLISH_REND:
  630. case CIRCUIT_PURPOSE_C_REND_READY_INTRO_ACKED:
  631. case CIRCUIT_PURPOSE_C_INTRODUCE_ACK_WAIT:
  632. /* rend and intro circs become dirty each time they
  633. * make an introduction attempt. so timestamp_dirty
  634. * will reflect the time since the last attempt.
  635. */
  636. if (victim->timestamp_dirty > cutoff.tv_sec)
  637. continue;
  638. break;
  639. }
  640. } else { /* circuit not open, consider recording failure as timeout */
  641. int first_hop_succeeded = TO_ORIGIN_CIRCUIT(victim)->cpath &&
  642. TO_ORIGIN_CIRCUIT(victim)->cpath->state == CPATH_STATE_OPEN;
  643. if (TO_ORIGIN_CIRCUIT(victim)->p_streams != NULL) {
  644. log_warn(LD_BUG, "Circuit %d (purpose %d, %s) has timed out, "
  645. "yet has attached streams!",
  646. TO_ORIGIN_CIRCUIT(victim)->global_identifier,
  647. victim->purpose,
  648. circuit_purpose_to_string(victim->purpose));
  649. tor_fragile_assert();
  650. continue;
  651. }
  652. if (circuit_timeout_want_to_count_circ(TO_ORIGIN_CIRCUIT(victim)) &&
  653. circuit_build_times_enough_to_compute(get_circuit_build_times())) {
  654. log_info(LD_CIRC,
  655. "Deciding to count the timeout for circuit %"PRIu32"\n",
  656. TO_ORIGIN_CIRCUIT(victim)->global_identifier);
  657. /* Circuits are allowed to last longer for measurement.
  658. * Switch their purpose and wait. */
  659. if (victim->purpose != CIRCUIT_PURPOSE_C_MEASURE_TIMEOUT) {
  660. circuit_build_times_mark_circ_as_measurement_only(TO_ORIGIN_CIRCUIT(
  661. victim));
  662. continue;
  663. }
  664. /*
  665. * If the circuit build time is much greater than we would have cut
  666. * it off at, we probably had a suspend event along this codepath,
  667. * and we should discard the value.
  668. */
  669. if (timercmp(&victim->timestamp_began, &extremely_old_cutoff, OP_LT)) {
  670. log_notice(LD_CIRC,
  671. "Extremely large value for circuit build timeout: %lds. "
  672. "Assuming clock jump. Purpose %d (%s)",
  673. (long)(now.tv_sec - victim->timestamp_began.tv_sec),
  674. victim->purpose,
  675. circuit_purpose_to_string(victim->purpose));
  676. } else if (circuit_build_times_count_close(
  677. get_circuit_build_times_mutable(),
  678. first_hop_succeeded,
  679. (time_t)victim->timestamp_created.tv_sec)) {
  680. circuit_build_times_set_timeout(get_circuit_build_times_mutable());
  681. }
  682. }
  683. }
  684. /* If this is a hidden service client circuit which is far enough along in
  685. * connecting to its destination, and we haven't already flagged it as
  686. * 'timed out', flag it so we'll launch another intro or rend circ, but
  687. * don't mark it for close yet.
  688. *
  689. * (Circs flagged as 'timed out' are given a much longer timeout
  690. * period above, so we won't close them in the next call to
  691. * circuit_expire_building.) */
  692. if (!(TO_ORIGIN_CIRCUIT(victim)->hs_circ_has_timed_out)) {
  693. switch (victim->purpose) {
  694. case CIRCUIT_PURPOSE_C_REND_READY:
  695. /* We only want to spare a rend circ if it has been specified in
  696. * an INTRODUCE1 cell sent to a hidden service. A circ's
  697. * pending_final_cpath field is non-NULL iff it is a rend circ
  698. * and we have tried to send an INTRODUCE1 cell specifying it.
  699. * Thus, if the pending_final_cpath field *is* NULL, then we
  700. * want to not spare it. */
  701. if (TO_ORIGIN_CIRCUIT(victim)->build_state &&
  702. TO_ORIGIN_CIRCUIT(victim)->build_state->pending_final_cpath ==
  703. NULL)
  704. break;
  705. /* fallthrough! */
  706. case CIRCUIT_PURPOSE_C_INTRODUCE_ACK_WAIT:
  707. case CIRCUIT_PURPOSE_C_REND_READY_INTRO_ACKED:
  708. /* If we have reached this line, we want to spare the circ for now. */
  709. log_info(LD_CIRC,"Marking circ %u (state %d:%s, purpose %d) "
  710. "as timed-out HS circ",
  711. (unsigned)victim->n_circ_id,
  712. victim->state, circuit_state_to_string(victim->state),
  713. victim->purpose);
  714. TO_ORIGIN_CIRCUIT(victim)->hs_circ_has_timed_out = 1;
  715. continue;
  716. default:
  717. break;
  718. }
  719. }
  720. /* If this is a service-side rendezvous circuit which is far
  721. * enough along in connecting to its destination, consider sparing
  722. * it. */
  723. if (!(TO_ORIGIN_CIRCUIT(victim)->hs_circ_has_timed_out) &&
  724. victim->purpose == CIRCUIT_PURPOSE_S_CONNECT_REND) {
  725. log_info(LD_CIRC,"Marking circ %u (state %d:%s, purpose %d) "
  726. "as timed-out HS circ; relaunching rendezvous attempt.",
  727. (unsigned)victim->n_circ_id,
  728. victim->state, circuit_state_to_string(victim->state),
  729. victim->purpose);
  730. TO_ORIGIN_CIRCUIT(victim)->hs_circ_has_timed_out = 1;
  731. hs_circ_retry_service_rendezvous_point(TO_ORIGIN_CIRCUIT(victim));
  732. continue;
  733. }
  734. if (victim->n_chan)
  735. log_info(LD_CIRC,
  736. "Abandoning circ %u %s:%u (state %d,%d:%s, purpose %d, "
  737. "len %d)", TO_ORIGIN_CIRCUIT(victim)->global_identifier,
  738. channel_get_canonical_remote_descr(victim->n_chan),
  739. (unsigned)victim->n_circ_id,
  740. TO_ORIGIN_CIRCUIT(victim)->has_opened,
  741. victim->state, circuit_state_to_string(victim->state),
  742. victim->purpose,
  743. TO_ORIGIN_CIRCUIT(victim)->build_state ?
  744. TO_ORIGIN_CIRCUIT(victim)->build_state->desired_path_len :
  745. -1);
  746. else
  747. log_info(LD_CIRC,
  748. "Abandoning circ %u %u (state %d,%d:%s, purpose %d, len %d)",
  749. TO_ORIGIN_CIRCUIT(victim)->global_identifier,
  750. (unsigned)victim->n_circ_id,
  751. TO_ORIGIN_CIRCUIT(victim)->has_opened,
  752. victim->state,
  753. circuit_state_to_string(victim->state), victim->purpose,
  754. TO_ORIGIN_CIRCUIT(victim)->build_state ?
  755. TO_ORIGIN_CIRCUIT(victim)->build_state->desired_path_len :
  756. -1);
  757. circuit_log_path(LOG_INFO,LD_CIRC,TO_ORIGIN_CIRCUIT(victim));
  758. if (victim->purpose == CIRCUIT_PURPOSE_C_MEASURE_TIMEOUT)
  759. circuit_mark_for_close(victim, END_CIRC_REASON_MEASUREMENT_EXPIRED);
  760. else
  761. circuit_mark_for_close(victim, END_CIRC_REASON_TIMEOUT);
  762. pathbias_count_timeout(TO_ORIGIN_CIRCUIT(victim));
  763. } SMARTLIST_FOREACH_END(victim);
  764. }
  765. /**
  766. * Mark for close all circuits that start here, that were built through a
  767. * guard we weren't sure if we wanted to use, and that have been waiting
  768. * around for way too long.
  769. */
  770. void
  771. circuit_expire_waiting_for_better_guard(void)
  772. {
  773. SMARTLIST_FOREACH_BEGIN(circuit_get_global_origin_circuit_list(),
  774. origin_circuit_t *, circ) {
  775. if (TO_CIRCUIT(circ)->marked_for_close)
  776. continue;
  777. if (circ->guard_state == NULL)
  778. continue;
  779. if (entry_guard_state_should_expire(circ->guard_state))
  780. circuit_mark_for_close(TO_CIRCUIT(circ), END_CIRC_REASON_NONE);
  781. } SMARTLIST_FOREACH_END(circ);
  782. }
  783. /** For debugging #8387: track when we last called
  784. * circuit_expire_old_circuits_clientside. */
  785. static time_t last_expired_clientside_circuits = 0;
  786. /**
  787. * As a diagnostic for bug 8387, log information about how many one-hop
  788. * circuits we have around that have been there for at least <b>age</b>
  789. * seconds. Log a few of them. Ignores Single Onion Service intro, it is
  790. * expected to be long-term one-hop circuits.
  791. */
  792. void
  793. circuit_log_ancient_one_hop_circuits(int age)
  794. {
  795. #define MAX_ANCIENT_ONEHOP_CIRCUITS_TO_LOG 10
  796. time_t now = time(NULL);
  797. time_t cutoff = now - age;
  798. int n_found = 0;
  799. smartlist_t *log_these = smartlist_new();
  800. const or_options_t *options = get_options();
  801. SMARTLIST_FOREACH_BEGIN(circuit_get_global_list(), circuit_t *, circ) {
  802. const origin_circuit_t *ocirc;
  803. if (! CIRCUIT_IS_ORIGIN(circ))
  804. continue;
  805. if (circ->timestamp_created.tv_sec >= cutoff)
  806. continue;
  807. /* Single Onion Services deliberately make long term one-hop intro
  808. * and rendezvous connections. Don't log the established ones. */
  809. if (rend_service_allow_non_anonymous_connection(options) &&
  810. (circ->purpose == CIRCUIT_PURPOSE_S_INTRO ||
  811. circ->purpose == CIRCUIT_PURPOSE_S_REND_JOINED))
  812. continue;
  813. ocirc = CONST_TO_ORIGIN_CIRCUIT(circ);
  814. if (ocirc->build_state && ocirc->build_state->onehop_tunnel) {
  815. ++n_found;
  816. if (smartlist_len(log_these) < MAX_ANCIENT_ONEHOP_CIRCUITS_TO_LOG)
  817. smartlist_add(log_these, (origin_circuit_t*) ocirc);
  818. }
  819. }
  820. SMARTLIST_FOREACH_END(circ);
  821. if (n_found == 0)
  822. goto done;
  823. log_notice(LD_HEARTBEAT,
  824. "Diagnostic for issue 8387: Found %d one-hop circuits more "
  825. "than %d seconds old! Logging %d...",
  826. n_found, age, smartlist_len(log_these));
  827. SMARTLIST_FOREACH_BEGIN(log_these, const origin_circuit_t *, ocirc) {
  828. char created[ISO_TIME_LEN+1];
  829. int stream_num;
  830. const edge_connection_t *conn;
  831. char *dirty = NULL;
  832. const circuit_t *circ = TO_CIRCUIT(ocirc);
  833. format_local_iso_time(created,
  834. (time_t)circ->timestamp_created.tv_sec);
  835. if (circ->timestamp_dirty) {
  836. char dirty_since[ISO_TIME_LEN+1];
  837. format_local_iso_time(dirty_since, circ->timestamp_dirty);
  838. tor_asprintf(&dirty, "Dirty since %s (%ld seconds vs %ld-second cutoff)",
  839. dirty_since, (long)(now - circ->timestamp_dirty),
  840. (long) options->MaxCircuitDirtiness);
  841. } else {
  842. dirty = tor_strdup("Not marked dirty");
  843. }
  844. log_notice(LD_HEARTBEAT, " #%d created at %s. %s, %s. %s for close. "
  845. "Package window: %d. "
  846. "%s for new conns. %s.",
  847. ocirc_sl_idx,
  848. created,
  849. circuit_state_to_string(circ->state),
  850. circuit_purpose_to_string(circ->purpose),
  851. circ->marked_for_close ? "Marked" : "Not marked",
  852. circ->package_window,
  853. ocirc->unusable_for_new_conns ? "Not usable" : "usable",
  854. dirty);
  855. tor_free(dirty);
  856. stream_num = 0;
  857. for (conn = ocirc->p_streams; conn; conn = conn->next_stream) {
  858. const connection_t *c = TO_CONN(conn);
  859. char stream_created[ISO_TIME_LEN+1];
  860. if (++stream_num >= 5)
  861. break;
  862. format_local_iso_time(stream_created, c->timestamp_created);
  863. log_notice(LD_HEARTBEAT, " Stream#%d created at %s. "
  864. "%s conn in state %s. "
  865. "It is %slinked and %sreading from a linked connection %p. "
  866. "Package window %d. "
  867. "%s for close (%s:%d). Hold-open is %sset. "
  868. "Has %ssent RELAY_END. %s on circuit.",
  869. stream_num,
  870. stream_created,
  871. conn_type_to_string(c->type),
  872. conn_state_to_string(c->type, c->state),
  873. c->linked ? "" : "not ",
  874. c->reading_from_linked_conn ? "": "not",
  875. c->linked_conn,
  876. conn->package_window,
  877. c->marked_for_close ? "Marked" : "Not marked",
  878. c->marked_for_close_file ? c->marked_for_close_file : "--",
  879. c->marked_for_close,
  880. c->hold_open_until_flushed ? "" : "not ",
  881. conn->edge_has_sent_end ? "" : "not ",
  882. conn->edge_blocked_on_circ ? "Blocked" : "Not blocked");
  883. if (! c->linked_conn)
  884. continue;
  885. c = c->linked_conn;
  886. log_notice(LD_HEARTBEAT, " Linked to %s connection in state %s "
  887. "(Purpose %d). %s for close (%s:%d). Hold-open is %sset. ",
  888. conn_type_to_string(c->type),
  889. conn_state_to_string(c->type, c->state),
  890. c->purpose,
  891. c->marked_for_close ? "Marked" : "Not marked",
  892. c->marked_for_close_file ? c->marked_for_close_file : "--",
  893. c->marked_for_close,
  894. c->hold_open_until_flushed ? "" : "not ");
  895. }
  896. } SMARTLIST_FOREACH_END(ocirc);
  897. log_notice(LD_HEARTBEAT, "It has been %ld seconds since I last called "
  898. "circuit_expire_old_circuits_clientside().",
  899. (long)(now - last_expired_clientside_circuits));
  900. done:
  901. smartlist_free(log_these);
  902. }
  903. /** Remove any elements in <b>needed_ports</b> that are handled by an
  904. * open or in-progress circuit.
  905. */
  906. void
  907. circuit_remove_handled_ports(smartlist_t *needed_ports)
  908. {
  909. int i;
  910. uint16_t *port;
  911. for (i = 0; i < smartlist_len(needed_ports); ++i) {
  912. port = smartlist_get(needed_ports, i);
  913. tor_assert(*port);
  914. if (circuit_stream_is_being_handled(NULL, *port,
  915. MIN_CIRCUITS_HANDLING_STREAM)) {
  916. log_debug(LD_CIRC,"Port %d is already being handled; removing.", *port);
  917. smartlist_del(needed_ports, i--);
  918. tor_free(port);
  919. } else {
  920. log_debug(LD_CIRC,"Port %d is not handled.", *port);
  921. }
  922. }
  923. }
  924. /** Return 1 if at least <b>min</b> general-purpose non-internal circuits
  925. * will have an acceptable exit node for exit stream <b>conn</b> if it
  926. * is defined, else for "*:port".
  927. * Else return 0.
  928. */
  929. int
  930. circuit_stream_is_being_handled(entry_connection_t *conn,
  931. uint16_t port, int min)
  932. {
  933. const node_t *exitnode;
  934. int num=0;
  935. time_t now = time(NULL);
  936. int need_uptime = smartlist_contains_int_as_string(
  937. get_options()->LongLivedPorts,
  938. conn ? conn->socks_request->port : port);
  939. SMARTLIST_FOREACH_BEGIN(circuit_get_global_list(), circuit_t *, circ) {
  940. if (CIRCUIT_IS_ORIGIN(circ) &&
  941. !circ->marked_for_close &&
  942. circ->purpose == CIRCUIT_PURPOSE_C_GENERAL &&
  943. (!circ->timestamp_dirty ||
  944. circ->timestamp_dirty + get_options()->MaxCircuitDirtiness > now)) {
  945. origin_circuit_t *origin_circ = TO_ORIGIN_CIRCUIT(circ);
  946. cpath_build_state_t *build_state = origin_circ->build_state;
  947. if (build_state->is_internal || build_state->onehop_tunnel)
  948. continue;
  949. if (origin_circ->unusable_for_new_conns)
  950. continue;
  951. if (origin_circ->isolation_values_set &&
  952. (conn == NULL ||
  953. !connection_edge_compatible_with_circuit(conn, origin_circ)))
  954. continue;
  955. exitnode = build_state_get_exit_node(build_state);
  956. if (exitnode && (!need_uptime || build_state->need_uptime)) {
  957. int ok;
  958. if (conn) {
  959. ok = connection_ap_can_use_exit(conn, exitnode);
  960. } else {
  961. addr_policy_result_t r;
  962. r = compare_tor_addr_to_node_policy(NULL, port, exitnode);
  963. ok = r != ADDR_POLICY_REJECTED && r != ADDR_POLICY_PROBABLY_REJECTED;
  964. }
  965. if (ok) {
  966. if (++num >= min)
  967. return 1;
  968. }
  969. }
  970. }
  971. }
  972. SMARTLIST_FOREACH_END(circ);
  973. return 0;
  974. }
  975. /** Don't keep more than this many unused open circuits around. */
  976. #define MAX_UNUSED_OPEN_CIRCUITS 14
  977. /* Return true if a circuit is available for use, meaning that it is open,
  978. * clean, usable for new multi-hop connections, and a general purpose origin
  979. * circuit.
  980. * Accept any kind of circuit, return false if the above conditions are not
  981. * met. */
  982. STATIC int
  983. circuit_is_available_for_use(const circuit_t *circ)
  984. {
  985. const origin_circuit_t *origin_circ;
  986. cpath_build_state_t *build_state;
  987. if (!CIRCUIT_IS_ORIGIN(circ))
  988. return 0; /* We first filter out only origin circuits before doing the
  989. following checks. */
  990. if (circ->marked_for_close)
  991. return 0; /* Don't mess with marked circs */
  992. if (circ->timestamp_dirty)
  993. return 0; /* Only count clean circs */
  994. if (circ->purpose != CIRCUIT_PURPOSE_C_GENERAL &&
  995. circ->purpose != CIRCUIT_PURPOSE_HS_VANGUARDS)
  996. return 0; /* We only pay attention to general purpose circuits.
  997. General purpose circuits are always origin circuits. */
  998. origin_circ = CONST_TO_ORIGIN_CIRCUIT(circ);
  999. if (origin_circ->unusable_for_new_conns)
  1000. return 0;
  1001. build_state = origin_circ->build_state;
  1002. if (build_state->onehop_tunnel)
  1003. return 0;
  1004. return 1;
  1005. }
  1006. /* Return true if we need any more exit circuits.
  1007. * needs_uptime and needs_capacity are set only if we need more exit circuits.
  1008. * Check if we know of a port that's been requested recently and no circuit
  1009. * is currently available that can handle it. */
  1010. STATIC int
  1011. needs_exit_circuits(time_t now, int *needs_uptime, int *needs_capacity)
  1012. {
  1013. return (!circuit_all_predicted_ports_handled(now, needs_uptime,
  1014. needs_capacity) &&
  1015. router_have_consensus_path() == CONSENSUS_PATH_EXIT);
  1016. }
  1017. /* Hidden services need at least this many internal circuits */
  1018. #define SUFFICIENT_UPTIME_INTERNAL_HS_SERVERS 3
  1019. /* Return true if we need any more hidden service server circuits.
  1020. * HS servers only need an internal circuit. */
  1021. STATIC int
  1022. needs_hs_server_circuits(time_t now, int num_uptime_internal)
  1023. {
  1024. if (!rend_num_services() && !hs_service_get_num_services()) {
  1025. /* No services, we don't need anything. */
  1026. goto no_need;
  1027. }
  1028. if (num_uptime_internal >= SUFFICIENT_UPTIME_INTERNAL_HS_SERVERS) {
  1029. /* We have sufficient amount of internal circuit. */
  1030. goto no_need;
  1031. }
  1032. if (router_have_consensus_path() == CONSENSUS_PATH_UNKNOWN) {
  1033. /* Consensus hasn't been checked or might be invalid so requesting
  1034. * internal circuits is not wise. */
  1035. goto no_need;
  1036. }
  1037. /* At this point, we need a certain amount of circuits and we will most
  1038. * likely use them for rendezvous so we note down the use of internal
  1039. * circuit for our prediction for circuit needing uptime and capacity. */
  1040. rep_hist_note_used_internal(now, 1, 1);
  1041. return 1;
  1042. no_need:
  1043. return 0;
  1044. }
  1045. /* We need at least this many internal circuits for hidden service clients */
  1046. #define SUFFICIENT_INTERNAL_HS_CLIENTS 3
  1047. /* We need at least this much uptime for internal circuits for hidden service
  1048. * clients */
  1049. #define SUFFICIENT_UPTIME_INTERNAL_HS_CLIENTS 2
  1050. /* Return true if we need any more hidden service client circuits.
  1051. * HS clients only need an internal circuit. */
  1052. STATIC int
  1053. needs_hs_client_circuits(time_t now, int *needs_uptime, int *needs_capacity,
  1054. int num_internal, int num_uptime_internal)
  1055. {
  1056. int used_internal_recently = rep_hist_get_predicted_internal(now,
  1057. needs_uptime,
  1058. needs_capacity);
  1059. int requires_uptime = num_uptime_internal <
  1060. SUFFICIENT_UPTIME_INTERNAL_HS_CLIENTS &&
  1061. needs_uptime;
  1062. return (used_internal_recently &&
  1063. (requires_uptime || num_internal < SUFFICIENT_INTERNAL_HS_CLIENTS) &&
  1064. router_have_consensus_path() != CONSENSUS_PATH_UNKNOWN);
  1065. }
  1066. /* This is how many circuits can be opened concurrently during the cbt learning
  1067. * phase. This number cannot exceed the tor-wide MAX_UNUSED_OPEN_CIRCUITS. */
  1068. #define DFLT_CBT_UNUSED_OPEN_CIRCS (10)
  1069. #define MIN_CBT_UNUSED_OPEN_CIRCS 0
  1070. #define MAX_CBT_UNUSED_OPEN_CIRCS MAX_UNUSED_OPEN_CIRCUITS
  1071. /* Return true if we need more circuits for a good build timeout.
  1072. * XXXX make the assumption that build timeout streams should be
  1073. * created whenever we can build internal circuits. */
  1074. STATIC int
  1075. needs_circuits_for_build(int num)
  1076. {
  1077. if (router_have_consensus_path() != CONSENSUS_PATH_UNKNOWN) {
  1078. if (num < networkstatus_get_param(NULL, "cbtmaxopencircs",
  1079. DFLT_CBT_UNUSED_OPEN_CIRCS,
  1080. MIN_CBT_UNUSED_OPEN_CIRCS,
  1081. MAX_CBT_UNUSED_OPEN_CIRCS) &&
  1082. !circuit_build_times_disabled(get_options()) &&
  1083. circuit_build_times_needs_circuits_now(get_circuit_build_times())) {
  1084. return 1;
  1085. }
  1086. }
  1087. return 0;
  1088. }
  1089. /**
  1090. * Launch the appropriate type of predicted circuit for hidden
  1091. * services, depending on our options.
  1092. */
  1093. static void
  1094. circuit_launch_predicted_hs_circ(int flags)
  1095. {
  1096. /* K.I.S.S. implementation of bug #23101: If we are using
  1097. * vanguards or pinned middles, pre-build a specific purpose
  1098. * for HS circs. */
  1099. if (circuit_should_use_vanguards(CIRCUIT_PURPOSE_HS_VANGUARDS)) {
  1100. circuit_launch(CIRCUIT_PURPOSE_HS_VANGUARDS, flags);
  1101. } else {
  1102. /* If no vanguards, then no HS-specific prebuilt circuits are needed.
  1103. * Normal GENERAL circs are fine */
  1104. circuit_launch(CIRCUIT_PURPOSE_C_GENERAL, flags);
  1105. }
  1106. }
  1107. /** Determine how many circuits we have open that are clean,
  1108. * Make sure it's enough for all the upcoming behaviors we predict we'll have.
  1109. * But put an upper bound on the total number of circuits.
  1110. */
  1111. static void
  1112. circuit_predict_and_launch_new(void)
  1113. {
  1114. int num=0, num_internal=0, num_uptime_internal=0;
  1115. int hidserv_needs_uptime=0, hidserv_needs_capacity=1;
  1116. int port_needs_uptime=0, port_needs_capacity=1;
  1117. time_t now = time(NULL);
  1118. int flags = 0;
  1119. /* Count how many of each type of circuit we currently have. */
  1120. SMARTLIST_FOREACH_BEGIN(circuit_get_global_list(), circuit_t *, circ) {
  1121. if (!circuit_is_available_for_use(circ))
  1122. continue;
  1123. num++;
  1124. cpath_build_state_t *build_state = TO_ORIGIN_CIRCUIT(circ)->build_state;
  1125. if (build_state->is_internal)
  1126. num_internal++;
  1127. if (build_state->need_uptime && build_state->is_internal)
  1128. num_uptime_internal++;
  1129. }
  1130. SMARTLIST_FOREACH_END(circ);
  1131. /* If that's enough, then stop now. */
  1132. if (num >= MAX_UNUSED_OPEN_CIRCUITS)
  1133. return;
  1134. if (needs_exit_circuits(now, &port_needs_uptime, &port_needs_capacity)) {
  1135. if (port_needs_uptime)
  1136. flags |= CIRCLAUNCH_NEED_UPTIME;
  1137. if (port_needs_capacity)
  1138. flags |= CIRCLAUNCH_NEED_CAPACITY;
  1139. log_info(LD_CIRC,
  1140. "Have %d clean circs (%d internal), need another exit circ.",
  1141. num, num_internal);
  1142. circuit_launch(CIRCUIT_PURPOSE_C_GENERAL, flags);
  1143. return;
  1144. }
  1145. if (needs_hs_server_circuits(now, num_uptime_internal)) {
  1146. flags = (CIRCLAUNCH_NEED_CAPACITY | CIRCLAUNCH_NEED_UPTIME |
  1147. CIRCLAUNCH_IS_INTERNAL);
  1148. log_info(LD_CIRC,
  1149. "Have %d clean circs (%d internal), need another internal "
  1150. "circ for my hidden service.",
  1151. num, num_internal);
  1152. circuit_launch_predicted_hs_circ(flags);
  1153. return;
  1154. }
  1155. if (needs_hs_client_circuits(now, &hidserv_needs_uptime,
  1156. &hidserv_needs_capacity,
  1157. num_internal, num_uptime_internal))
  1158. {
  1159. if (hidserv_needs_uptime)
  1160. flags |= CIRCLAUNCH_NEED_UPTIME;
  1161. if (hidserv_needs_capacity)
  1162. flags |= CIRCLAUNCH_NEED_CAPACITY;
  1163. flags |= CIRCLAUNCH_IS_INTERNAL;
  1164. log_info(LD_CIRC,
  1165. "Have %d clean circs (%d uptime-internal, %d internal), need"
  1166. " another hidden service circ.",
  1167. num, num_uptime_internal, num_internal);
  1168. circuit_launch_predicted_hs_circ(flags);
  1169. return;
  1170. }
  1171. if (needs_circuits_for_build(num)) {
  1172. flags = CIRCLAUNCH_NEED_CAPACITY;
  1173. /* if there are no exits in the consensus, make timeout
  1174. * circuits internal */
  1175. if (router_have_consensus_path() == CONSENSUS_PATH_INTERNAL)
  1176. flags |= CIRCLAUNCH_IS_INTERNAL;
  1177. log_info(LD_CIRC,
  1178. "Have %d clean circs need another buildtime test circ.", num);
  1179. circuit_launch(CIRCUIT_PURPOSE_C_GENERAL, flags);
  1180. return;
  1181. }
  1182. }
  1183. /** Build a new test circuit every 5 minutes */
  1184. #define TESTING_CIRCUIT_INTERVAL 300
  1185. /** This function is called once a second, if router_have_minimum_dir_info()
  1186. * is true. Its job is to make sure all services we offer have enough circuits
  1187. * available. Some services just want enough circuits for current tasks,
  1188. * whereas others want a minimum set of idle circuits hanging around.
  1189. */
  1190. void
  1191. circuit_build_needed_circs(time_t now)
  1192. {
  1193. const or_options_t *options = get_options();
  1194. /* launch a new circ for any pending streams that need one
  1195. * XXXX make the assumption that (some) AP streams (i.e. HS clients)
  1196. * don't require an exit circuit, review in #13814.
  1197. * This allows HSs to function in a consensus without exits. */
  1198. if (router_have_consensus_path() != CONSENSUS_PATH_UNKNOWN)
  1199. connection_ap_rescan_and_attach_pending();
  1200. circuit_expire_old_circs_as_needed(now);
  1201. if (!options->DisablePredictedCircuits)
  1202. circuit_predict_and_launch_new();
  1203. }
  1204. /**
  1205. * Called once a second either directly or from
  1206. * circuit_build_needed_circs(). As appropriate (once per NewCircuitPeriod)
  1207. * resets failure counts and expires old circuits.
  1208. */
  1209. void
  1210. circuit_expire_old_circs_as_needed(time_t now)
  1211. {
  1212. static time_t time_to_expire_and_reset = 0;
  1213. if (time_to_expire_and_reset < now) {
  1214. circuit_reset_failure_count(1);
  1215. time_to_expire_and_reset = now + get_options()->NewCircuitPeriod;
  1216. if (proxy_mode(get_options()))
  1217. addressmap_clean(now);
  1218. circuit_expire_old_circuits_clientside();
  1219. #if 0 /* disable for now, until predict-and-launch-new can cull leftovers */
  1220. /* If we ever re-enable, this has to move into
  1221. * circuit_build_needed_circs */
  1222. circ = circuit_get_youngest_clean_open(CIRCUIT_PURPOSE_C_GENERAL);
  1223. if (get_options()->RunTesting &&
  1224. circ &&
  1225. circ->timestamp_began.tv_sec + TESTING_CIRCUIT_INTERVAL < now) {
  1226. log_fn(LOG_INFO,"Creating a new testing circuit.");
  1227. circuit_launch(CIRCUIT_PURPOSE_C_GENERAL, 0);
  1228. }
  1229. #endif /* 0 */
  1230. }
  1231. }
  1232. /** If the stream <b>conn</b> is a member of any of the linked
  1233. * lists of <b>circ</b>, then remove it from the list.
  1234. */
  1235. void
  1236. circuit_detach_stream(circuit_t *circ, edge_connection_t *conn)
  1237. {
  1238. edge_connection_t *prevconn;
  1239. tor_assert(circ);
  1240. tor_assert(conn);
  1241. if (conn->base_.type == CONN_TYPE_AP) {
  1242. entry_connection_t *entry_conn = EDGE_TO_ENTRY_CONN(conn);
  1243. entry_conn->may_use_optimistic_data = 0;
  1244. }
  1245. conn->cpath_layer = NULL; /* don't keep a stale pointer */
  1246. conn->on_circuit = NULL;
  1247. if (CIRCUIT_IS_ORIGIN(circ)) {
  1248. origin_circuit_t *origin_circ = TO_ORIGIN_CIRCUIT(circ);
  1249. int removed = 0;
  1250. if (conn == origin_circ->p_streams) {
  1251. origin_circ->p_streams = conn->next_stream;
  1252. removed = 1;
  1253. } else {
  1254. for (prevconn = origin_circ->p_streams;
  1255. prevconn && prevconn->next_stream && prevconn->next_stream != conn;
  1256. prevconn = prevconn->next_stream)
  1257. ;
  1258. if (prevconn && prevconn->next_stream) {
  1259. prevconn->next_stream = conn->next_stream;
  1260. removed = 1;
  1261. }
  1262. }
  1263. if (removed) {
  1264. log_debug(LD_APP, "Removing stream %d from circ %u",
  1265. conn->stream_id, (unsigned)circ->n_circ_id);
  1266. /* If the stream was removed, and it was a rend stream, decrement the
  1267. * number of streams on the circuit associated with the rend service.
  1268. */
  1269. if (circ->purpose == CIRCUIT_PURPOSE_S_REND_JOINED) {
  1270. hs_dec_rdv_stream_counter(origin_circ);
  1271. }
  1272. return;
  1273. }
  1274. } else {
  1275. or_circuit_t *or_circ = TO_OR_CIRCUIT(circ);
  1276. if (conn == or_circ->n_streams) {
  1277. or_circ->n_streams = conn->next_stream;
  1278. return;
  1279. }
  1280. if (conn == or_circ->resolving_streams) {
  1281. or_circ->resolving_streams = conn->next_stream;
  1282. return;
  1283. }
  1284. for (prevconn = or_circ->n_streams;
  1285. prevconn && prevconn->next_stream && prevconn->next_stream != conn;
  1286. prevconn = prevconn->next_stream)
  1287. ;
  1288. if (prevconn && prevconn->next_stream) {
  1289. prevconn->next_stream = conn->next_stream;
  1290. return;
  1291. }
  1292. for (prevconn = or_circ->resolving_streams;
  1293. prevconn && prevconn->next_stream && prevconn->next_stream != conn;
  1294. prevconn = prevconn->next_stream)
  1295. ;
  1296. if (prevconn && prevconn->next_stream) {
  1297. prevconn->next_stream = conn->next_stream;
  1298. return;
  1299. }
  1300. }
  1301. log_warn(LD_BUG,"Edge connection not in circuit's list.");
  1302. /* Don't give an error here; it's harmless. */
  1303. tor_fragile_assert();
  1304. }
  1305. /** Find each circuit that has been unused for too long, or dirty
  1306. * for too long and has no streams on it: mark it for close.
  1307. */
  1308. static void
  1309. circuit_expire_old_circuits_clientside(void)
  1310. {
  1311. struct timeval cutoff, now;
  1312. tor_gettimeofday(&now);
  1313. last_expired_clientside_circuits = now.tv_sec;
  1314. SMARTLIST_FOREACH_BEGIN(circuit_get_global_list(), circuit_t *, circ) {
  1315. if (circ->marked_for_close || !CIRCUIT_IS_ORIGIN(circ))
  1316. continue;
  1317. cutoff = now;
  1318. cutoff.tv_sec -= TO_ORIGIN_CIRCUIT(circ)->circuit_idle_timeout;
  1319. /* If the circuit has been dirty for too long, and there are no streams
  1320. * on it, mark it for close.
  1321. */
  1322. if (circ->timestamp_dirty &&
  1323. circ->timestamp_dirty + get_options()->MaxCircuitDirtiness <
  1324. now.tv_sec &&
  1325. !TO_ORIGIN_CIRCUIT(circ)->p_streams /* nothing attached */ ) {
  1326. log_debug(LD_CIRC, "Closing n_circ_id %u (dirty %ld sec ago, "
  1327. "purpose %d)",
  1328. (unsigned)circ->n_circ_id,
  1329. (long)(now.tv_sec - circ->timestamp_dirty),
  1330. circ->purpose);
  1331. /* Don't do this magic for testing circuits. Their death is governed
  1332. * by circuit_expire_building */
  1333. if (circ->purpose != CIRCUIT_PURPOSE_PATH_BIAS_TESTING)
  1334. circuit_mark_for_close(circ, END_CIRC_REASON_FINISHED);
  1335. } else if (!circ->timestamp_dirty && circ->state == CIRCUIT_STATE_OPEN) {
  1336. if (timercmp(&circ->timestamp_began, &cutoff, OP_LT)) {
  1337. if (circ->purpose == CIRCUIT_PURPOSE_C_GENERAL ||
  1338. circ->purpose == CIRCUIT_PURPOSE_C_HSDIR_GET ||
  1339. circ->purpose == CIRCUIT_PURPOSE_S_HSDIR_POST ||
  1340. circ->purpose == CIRCUIT_PURPOSE_HS_VANGUARDS ||
  1341. circ->purpose == CIRCUIT_PURPOSE_C_MEASURE_TIMEOUT ||
  1342. circ->purpose == CIRCUIT_PURPOSE_S_ESTABLISH_INTRO ||
  1343. circ->purpose == CIRCUIT_PURPOSE_TESTING ||
  1344. (circ->purpose >= CIRCUIT_PURPOSE_C_INTRODUCING &&
  1345. circ->purpose <= CIRCUIT_PURPOSE_C_REND_READY_INTRO_ACKED) ||
  1346. circ->purpose == CIRCUIT_PURPOSE_S_CONNECT_REND) {
  1347. log_info(LD_CIRC,
  1348. "Closing circuit %"PRIu32
  1349. " that has been unused for %ld msec.",
  1350. TO_ORIGIN_CIRCUIT(circ)->global_identifier,
  1351. tv_mdiff(&circ->timestamp_began, &now));
  1352. circuit_mark_for_close(circ, END_CIRC_REASON_FINISHED);
  1353. } else if (!TO_ORIGIN_CIRCUIT(circ)->is_ancient) {
  1354. /* Server-side rend joined circuits can end up really old, because
  1355. * they are reused by clients for longer than normal. The client
  1356. * controls their lifespan. (They never become dirty, because
  1357. * connection_exit_begin_conn() never marks anything as dirty.)
  1358. * Similarly, server-side intro circuits last a long time. */
  1359. if (circ->purpose != CIRCUIT_PURPOSE_S_REND_JOINED &&
  1360. circ->purpose != CIRCUIT_PURPOSE_S_INTRO) {
  1361. log_notice(LD_CIRC,
  1362. "Ancient non-dirty circuit %d is still around after "
  1363. "%ld milliseconds. Purpose: %d (%s)",
  1364. TO_ORIGIN_CIRCUIT(circ)->global_identifier,
  1365. tv_mdiff(&circ->timestamp_began, &now),
  1366. circ->purpose,
  1367. circuit_purpose_to_string(circ->purpose));
  1368. TO_ORIGIN_CIRCUIT(circ)->is_ancient = 1;
  1369. }
  1370. }
  1371. }
  1372. }
  1373. } SMARTLIST_FOREACH_END(circ);
  1374. }
  1375. /** How long do we wait before killing circuits with the properties
  1376. * described below?
  1377. *
  1378. * Probably we could choose a number here as low as 5 to 10 seconds,
  1379. * since these circs are used for begindir, and a) generally you either
  1380. * ask another begindir question right after or you don't for a long time,
  1381. * b) clients at least through 0.2.1.x choose from the whole set of
  1382. * directory mirrors at each choice, and c) re-establishing a one-hop
  1383. * circuit via create-fast is a light operation assuming the TLS conn is
  1384. * still there.
  1385. *
  1386. * I expect "b" to go away one day when we move to using directory
  1387. * guards, but I think "a" and "c" are good enough reasons that a low
  1388. * number is safe even then.
  1389. */
  1390. #define IDLE_ONE_HOP_CIRC_TIMEOUT 60
  1391. /** Find each non-origin circuit that has been unused for too long,
  1392. * has no streams on it, came from a client, and ends here: mark it
  1393. * for close.
  1394. */
  1395. void
  1396. circuit_expire_old_circuits_serverside(time_t now)
  1397. {
  1398. or_circuit_t *or_circ;
  1399. time_t cutoff = now - IDLE_ONE_HOP_CIRC_TIMEOUT;
  1400. SMARTLIST_FOREACH_BEGIN(circuit_get_global_list(), circuit_t *, circ) {
  1401. if (circ->marked_for_close || CIRCUIT_IS_ORIGIN(circ))
  1402. continue;
  1403. or_circ = TO_OR_CIRCUIT(circ);
  1404. /* If the circuit has been idle for too long, and there are no streams
  1405. * on it, and it ends here, and it used a create_fast, mark it for close.
  1406. */
  1407. if (or_circ->p_chan && channel_is_client(or_circ->p_chan) &&
  1408. !circ->n_chan &&
  1409. !or_circ->n_streams && !or_circ->resolving_streams &&
  1410. channel_when_last_xmit(or_circ->p_chan) <= cutoff) {
  1411. log_info(LD_CIRC, "Closing circ_id %u (empty %d secs ago)",
  1412. (unsigned)or_circ->p_circ_id,
  1413. (int)(now - channel_when_last_xmit(or_circ->p_chan)));
  1414. circuit_mark_for_close(circ, END_CIRC_REASON_FINISHED);
  1415. }
  1416. }
  1417. SMARTLIST_FOREACH_END(circ);
  1418. }
  1419. /** Number of testing circuits we want open before testing our bandwidth. */
  1420. #define NUM_PARALLEL_TESTING_CIRCS 4
  1421. /** True iff we've ever had enough testing circuits open to test our
  1422. * bandwidth. */
  1423. static int have_performed_bandwidth_test = 0;
  1424. /** Reset have_performed_bandwidth_test, so we'll start building
  1425. * testing circuits again so we can exercise our bandwidth. */
  1426. void
  1427. reset_bandwidth_test(void)
  1428. {
  1429. have_performed_bandwidth_test = 0;
  1430. }
  1431. /** Return 1 if we've already exercised our bandwidth, or if we
  1432. * have fewer than NUM_PARALLEL_TESTING_CIRCS testing circuits
  1433. * established or on the way. Else return 0.
  1434. */
  1435. int
  1436. circuit_enough_testing_circs(void)
  1437. {
  1438. int num = 0;
  1439. if (have_performed_bandwidth_test)
  1440. return 1;
  1441. SMARTLIST_FOREACH_BEGIN(circuit_get_global_list(), circuit_t *, circ) {
  1442. if (!circ->marked_for_close && CIRCUIT_IS_ORIGIN(circ) &&
  1443. circ->purpose == CIRCUIT_PURPOSE_TESTING &&
  1444. circ->state == CIRCUIT_STATE_OPEN)
  1445. num++;
  1446. }
  1447. SMARTLIST_FOREACH_END(circ);
  1448. return num >= NUM_PARALLEL_TESTING_CIRCS;
  1449. }
  1450. /** A testing circuit has completed. Take whatever stats we want.
  1451. * Noticing reachability is taken care of in onionskin_answer(),
  1452. * so there's no need to record anything here. But if we still want
  1453. * to do the bandwidth test, and we now have enough testing circuits
  1454. * open, do it.
  1455. */
  1456. static void
  1457. circuit_testing_opened(origin_circuit_t *circ)
  1458. {
  1459. if (have_performed_bandwidth_test ||
  1460. !check_whether_orport_reachable(get_options())) {
  1461. /* either we've already done everything we want with testing circuits,
  1462. * or this testing circuit became open due to a fluke, e.g. we picked
  1463. * a last hop where we already had the connection open due to an
  1464. * outgoing local circuit. */
  1465. circuit_mark_for_close(TO_CIRCUIT(circ), END_CIRC_AT_ORIGIN);
  1466. } else if (circuit_enough_testing_circs()) {
  1467. router_perform_bandwidth_test(NUM_PARALLEL_TESTING_CIRCS, time(NULL));
  1468. have_performed_bandwidth_test = 1;
  1469. } else
  1470. router_do_reachability_checks(1, 0);
  1471. }
  1472. /** A testing circuit has failed to build. Take whatever stats we want. */
  1473. static void
  1474. circuit_testing_failed(origin_circuit_t *circ, int at_last_hop)
  1475. {
  1476. const or_options_t *options = get_options();
  1477. if (server_mode(options) && check_whether_orport_reachable(options))
  1478. return;
  1479. log_info(LD_GENERAL,
  1480. "Our testing circuit (to see if your ORPort is reachable) "
  1481. "has failed. I'll try again later.");
  1482. /* These aren't used yet. */
  1483. (void)circ;
  1484. (void)at_last_hop;
  1485. }
  1486. /** The circuit <b>circ</b> has just become open. Take the next
  1487. * step: for rendezvous circuits, we pass circ to the appropriate
  1488. * function in rendclient or rendservice. For general circuits, we
  1489. * call connection_ap_attach_pending, which looks for pending streams
  1490. * that could use circ.
  1491. */
  1492. void
  1493. circuit_has_opened(origin_circuit_t *circ)
  1494. {
  1495. control_event_circuit_status(circ, CIRC_EVENT_BUILT, 0);
  1496. /* Remember that this circuit has finished building. Now if we start
  1497. * it building again later (e.g. by extending it), we will know not
  1498. * to consider its build time. */
  1499. circ->has_opened = 1;
  1500. switch (TO_CIRCUIT(circ)->purpose) {
  1501. case CIRCUIT_PURPOSE_C_ESTABLISH_REND:
  1502. hs_client_circuit_has_opened(circ);
  1503. /* Start building an intro circ if we don't have one yet. */
  1504. connection_ap_attach_pending(1);
  1505. /* This isn't a call to circuit_try_attaching_streams because a
  1506. * circuit in _C_ESTABLISH_REND state isn't connected to its
  1507. * hidden service yet, thus we can't attach streams to it yet,
  1508. * thus circuit_try_attaching_streams would always clear the
  1509. * circuit's isolation state. circuit_try_attaching_streams is
  1510. * called later, when the rend circ enters _C_REND_JOINED
  1511. * state. */
  1512. break;
  1513. case CIRCUIT_PURPOSE_C_INTRODUCING:
  1514. hs_client_circuit_has_opened(circ);
  1515. break;
  1516. case CIRCUIT_PURPOSE_C_GENERAL:
  1517. case CIRCUIT_PURPOSE_C_HSDIR_GET:
  1518. case CIRCUIT_PURPOSE_S_HSDIR_POST:
  1519. /* Tell any AP connections that have been waiting for a new
  1520. * circuit that one is ready. */
  1521. circuit_try_attaching_streams(circ);
  1522. break;
  1523. case CIRCUIT_PURPOSE_S_ESTABLISH_INTRO:
  1524. /* at the service, waiting for introductions */
  1525. hs_service_circuit_has_opened(circ);
  1526. break;
  1527. case CIRCUIT_PURPOSE_S_CONNECT_REND:
  1528. /* at the service, connecting to rend point */
  1529. hs_service_circuit_has_opened(circ);
  1530. break;
  1531. case CIRCUIT_PURPOSE_TESTING:
  1532. circuit_testing_opened(circ);
  1533. break;
  1534. /* default:
  1535. * This won't happen in normal operation, but might happen if the
  1536. * controller did it. Just let it slide. */
  1537. }
  1538. }
  1539. /** If the stream-isolation state of <b>circ</b> can be cleared, clear
  1540. * it. Return non-zero iff <b>circ</b>'s isolation state was cleared. */
  1541. static int
  1542. circuit_try_clearing_isolation_state(origin_circuit_t *circ)
  1543. {
  1544. if (/* The circuit may have become non-open if it was cannibalized.*/
  1545. circ->base_.state == CIRCUIT_STATE_OPEN &&
  1546. /* If !isolation_values_set, there is nothing to clear. */
  1547. circ->isolation_values_set &&
  1548. /* It's not legal to clear a circuit's isolation info if it's ever had
  1549. * streams attached */
  1550. !circ->isolation_any_streams_attached) {
  1551. /* If we have any isolation information set on this circuit, and
  1552. * we didn't manage to attach any streams to it, then we can
  1553. * and should clear it and try again. */
  1554. circuit_clear_isolation(circ);
  1555. return 1;
  1556. } else {
  1557. return 0;
  1558. }
  1559. }
  1560. /** Called when a circuit becomes ready for streams to be attached to
  1561. * it. */
  1562. void
  1563. circuit_try_attaching_streams(origin_circuit_t *circ)
  1564. {
  1565. /* Attach streams to this circuit if we can. */
  1566. connection_ap_attach_pending(1);
  1567. /* The call to circuit_try_clearing_isolation_state here will do
  1568. * nothing and return 0 if we didn't attach any streams to circ
  1569. * above. */
  1570. if (circuit_try_clearing_isolation_state(circ)) {
  1571. /* Maybe *now* we can attach some streams to this circuit. */
  1572. connection_ap_attach_pending(1);
  1573. }
  1574. }
  1575. /** Called whenever a circuit could not be successfully built.
  1576. */
  1577. void
  1578. circuit_build_failed(origin_circuit_t *circ)
  1579. {
  1580. channel_t *n_chan = NULL;
  1581. /* we should examine circ and see if it failed because of
  1582. * the last hop or an earlier hop. then use this info below.
  1583. */
  1584. int failed_at_last_hop = 0;
  1585. /* First, check to see if this was a path failure, rather than build
  1586. * failure.
  1587. *
  1588. * Note that we deliberately use circuit_get_cpath_len() (and not
  1589. * circuit_get_cpath_opened_len()) because we only want to ensure
  1590. * that a full path is *chosen*. This is different than a full path
  1591. * being *built*. We only want to count *build* failures below.
  1592. *
  1593. * Path selection failures can happen spuriously for a number
  1594. * of reasons (such as aggressive/invalid user-specified path
  1595. * restrictions in the torrc, insufficient microdescriptors, and
  1596. * non-user reasons like exitpolicy issues), and so should not be
  1597. * counted as failures below.
  1598. */
  1599. if (circuit_get_cpath_len(circ) < circ->build_state->desired_path_len) {
  1600. static ratelim_t pathfail_limit = RATELIM_INIT(3600);
  1601. log_fn_ratelim(&pathfail_limit, LOG_NOTICE, LD_CIRC,
  1602. "Our circuit %u (id: %" PRIu32 ") died due to an invalid "
  1603. "selected path, purpose %s. This may be a torrc "
  1604. "configuration issue, or a bug.",
  1605. TO_CIRCUIT(circ)->n_circ_id, circ->global_identifier,
  1606. circuit_purpose_to_string(TO_CIRCUIT(circ)->purpose));
  1607. /* If the path failed on an RP, retry it. */
  1608. if (TO_CIRCUIT(circ)->purpose == CIRCUIT_PURPOSE_S_CONNECT_REND)
  1609. hs_circ_retry_service_rendezvous_point(circ);
  1610. /* In all other cases, just bail. The rest is just failure accounting
  1611. * that we don't want to do */
  1612. return;
  1613. }
  1614. /* If the last hop isn't open, and the second-to-last is, we failed
  1615. * at the last hop. */
  1616. if (circ->cpath &&
  1617. circ->cpath->prev->state != CPATH_STATE_OPEN &&
  1618. circ->cpath->prev->prev->state == CPATH_STATE_OPEN) {
  1619. failed_at_last_hop = 1;
  1620. }
  1621. /* Check if we failed at first hop */
  1622. if (circ->cpath &&
  1623. circ->cpath->state != CPATH_STATE_OPEN &&
  1624. ! circ->base_.received_destroy) {
  1625. /* We failed at the first hop for some reason other than a DESTROY cell.
  1626. * If there's an OR connection to blame, blame it. Also, avoid this relay
  1627. * for a while, and fail any one-hop directory fetches destined for it. */
  1628. const char *n_chan_ident = circ->cpath->extend_info->identity_digest;
  1629. tor_assert(n_chan_ident);
  1630. int already_marked = 0;
  1631. if (circ->base_.n_chan) {
  1632. n_chan = circ->base_.n_chan;
  1633. if (n_chan->is_bad_for_new_circs) {
  1634. /* We only want to blame this router when a fresh healthy
  1635. * connection fails. So don't mark this router as newly failed,
  1636. * since maybe this was just an old circuit attempt that's
  1637. * finally timing out now. Also, there's no need to blow away
  1638. * circuits/streams/etc, since the failure of an unhealthy conn
  1639. * doesn't tell us much about whether a healthy conn would
  1640. * succeed. */
  1641. already_marked = 1;
  1642. }
  1643. log_info(LD_OR,
  1644. "Our circuit %u (id: %" PRIu32 ") failed to get a response "
  1645. "from the first hop (%s). I'm going to try to rotate to a "
  1646. "better connection.",
  1647. TO_CIRCUIT(circ)->n_circ_id, circ->global_identifier,
  1648. channel_get_canonical_remote_descr(n_chan));
  1649. n_chan->is_bad_for_new_circs = 1;
  1650. } else {
  1651. log_info(LD_OR,
  1652. "Our circuit %u (id: %" PRIu32 ") died before the first hop "
  1653. "with no connection",
  1654. TO_CIRCUIT(circ)->n_circ_id, circ->global_identifier);
  1655. }
  1656. if (!already_marked) {
  1657. /*
  1658. * If we have guard state (new guard API) and our path selection
  1659. * code actually chose a full path, then blame the failure of this
  1660. * circuit on the guard.
  1661. */
  1662. if (circ->guard_state)
  1663. entry_guard_failed(&circ->guard_state);
  1664. /* if there are any one-hop streams waiting on this circuit, fail
  1665. * them now so they can retry elsewhere. */
  1666. connection_ap_fail_onehop(n_chan_ident, circ->build_state);
  1667. }
  1668. }
  1669. switch (circ->base_.purpose) {
  1670. case CIRCUIT_PURPOSE_C_HSDIR_GET:
  1671. case CIRCUIT_PURPOSE_S_HSDIR_POST:
  1672. case CIRCUIT_PURPOSE_C_GENERAL:
  1673. /* If we never built the circuit, note it as a failure. */
  1674. circuit_increment_failure_count();
  1675. if (failed_at_last_hop) {
  1676. /* Make sure any streams that demand our last hop as their exit
  1677. * know that it's unlikely to happen. */
  1678. circuit_discard_optional_exit_enclaves(circ->cpath->prev->extend_info);
  1679. }
  1680. break;
  1681. case CIRCUIT_PURPOSE_TESTING:
  1682. circuit_testing_failed(circ, failed_at_last_hop);
  1683. break;
  1684. case CIRCUIT_PURPOSE_S_ESTABLISH_INTRO:
  1685. /* at the service, waiting for introductions */
  1686. if (circ->base_.state != CIRCUIT_STATE_OPEN) {
  1687. circuit_increment_failure_count();
  1688. }
  1689. /* no need to care here, because the service will rebuild intro
  1690. * points periodically. */
  1691. break;
  1692. case CIRCUIT_PURPOSE_C_INTRODUCING:
  1693. /* at the client, connecting to intro point */
  1694. /* Don't increment failure count, since the service may have picked
  1695. * the introduction point maliciously */
  1696. /* The client will pick a new intro point when this one dies, if
  1697. * the stream in question still cares. No need to act here. */
  1698. break;
  1699. case CIRCUIT_PURPOSE_C_ESTABLISH_REND:
  1700. /* at the client, waiting for the service */
  1701. circuit_increment_failure_count();
  1702. /* the client will pick a new rend point when this one dies, if
  1703. * the stream in question still cares. No need to act here. */
  1704. break;
  1705. case CIRCUIT_PURPOSE_S_CONNECT_REND:
  1706. /* at the service, connecting to rend point */
  1707. /* Don't increment failure count, since the client may have picked
  1708. * the rendezvous point maliciously */
  1709. log_info(LD_REND,
  1710. "Couldn't connect to the client's chosen rend point %s "
  1711. "(%s hop failed).",
  1712. escaped(build_state_get_exit_nickname(circ->build_state)),
  1713. failed_at_last_hop?"last":"non-last");
  1714. hs_circ_retry_service_rendezvous_point(circ);
  1715. break;
  1716. /* default:
  1717. * This won't happen in normal operation, but might happen if the
  1718. * controller did it. Just let it slide. */
  1719. }
  1720. }
  1721. /** Number of consecutive failures so far; should only be touched by
  1722. * circuit_launch_new and circuit_*_failure_count.
  1723. */
  1724. static int n_circuit_failures = 0;
  1725. /** Before the last time we called circuit_reset_failure_count(), were
  1726. * there a lot of failures? */
  1727. static int did_circs_fail_last_period = 0;
  1728. /** Don't retry launching a new circuit if we try this many times with no
  1729. * success. */
  1730. #define MAX_CIRCUIT_FAILURES 5
  1731. /** Launch a new circuit; see circuit_launch_by_extend_info() for
  1732. * details on arguments. */
  1733. origin_circuit_t *
  1734. circuit_launch(uint8_t purpose, int flags)
  1735. {
  1736. return circuit_launch_by_extend_info(purpose, NULL, flags);
  1737. }
  1738. /* Do we have enough descriptors to build paths?
  1739. * If need_exit is true, return 1 if we can build exit paths.
  1740. * (We need at least one Exit in the consensus to build exit paths.)
  1741. * If need_exit is false, return 1 if we can build internal paths.
  1742. */
  1743. static int
  1744. have_enough_path_info(int need_exit)
  1745. {
  1746. if (need_exit)
  1747. return router_have_consensus_path() == CONSENSUS_PATH_EXIT;
  1748. else
  1749. return router_have_consensus_path() != CONSENSUS_PATH_UNKNOWN;
  1750. }
  1751. /**
  1752. * Tell us if a circuit is a hidden service circuit.
  1753. */
  1754. int
  1755. circuit_purpose_is_hidden_service(uint8_t purpose)
  1756. {
  1757. if (purpose == CIRCUIT_PURPOSE_HS_VANGUARDS) {
  1758. return 1;
  1759. }
  1760. /* Client-side purpose */
  1761. if (purpose >= CIRCUIT_PURPOSE_C_HS_MIN_ &&
  1762. purpose <= CIRCUIT_PURPOSE_C_HS_MAX_) {
  1763. return 1;
  1764. }
  1765. /* Service-side purpose */
  1766. if (purpose >= CIRCUIT_PURPOSE_S_HS_MIN_ &&
  1767. purpose <= CIRCUIT_PURPOSE_S_HS_MAX_) {
  1768. return 1;
  1769. }
  1770. return 0;
  1771. }
  1772. /**
  1773. * Return true if this circuit purpose should use vanguards
  1774. * or pinned Layer2 or Layer3 guards.
  1775. *
  1776. * This function takes both the circuit purpose and the
  1777. * torrc options for pinned middles/vanguards into account
  1778. * (ie: the circuit must be a hidden service circuit and
  1779. * vanguards/pinned middles must be enabled for it to return
  1780. * true).
  1781. */
  1782. int
  1783. circuit_should_use_vanguards(uint8_t purpose)
  1784. {
  1785. const or_options_t *options = get_options();
  1786. /* Only hidden service circuits use vanguards */
  1787. if (!circuit_purpose_is_hidden_service(purpose))
  1788. return 0;
  1789. /* Pinned middles are effectively vanguards */
  1790. if (options->HSLayer2Nodes || options->HSLayer3Nodes)
  1791. return 1;
  1792. return 0;
  1793. }
  1794. /**
  1795. * Return true for the set of conditions for which it is OK to use
  1796. * a cannibalized circuit.
  1797. *
  1798. * Don't cannibalize for onehops, or certain purposes.
  1799. */
  1800. static int
  1801. circuit_should_cannibalize_to_build(uint8_t purpose_to_build,
  1802. int has_extend_info,
  1803. int onehop_tunnel)
  1804. {
  1805. /* Do not try to cannibalize if this is a one hop circuit. */
  1806. if (onehop_tunnel) {
  1807. return 0;
  1808. }
  1809. /* Don't try to cannibalize for general purpose circuits that do not
  1810. * specify a custom exit. */
  1811. if (purpose_to_build == CIRCUIT_PURPOSE_C_GENERAL && !has_extend_info) {
  1812. return 0;
  1813. }
  1814. /* Don't cannibalize for testing circuits. We want to see if they
  1815. * complete normally. Also don't cannibalize for vanguard-purpose
  1816. * circuits, since those are specially pre-built for later
  1817. * cannibalization by the actual specific circuit types that need
  1818. * vanguards.
  1819. */
  1820. if (purpose_to_build == CIRCUIT_PURPOSE_TESTING ||
  1821. purpose_to_build == CIRCUIT_PURPOSE_HS_VANGUARDS) {
  1822. return 0;
  1823. }
  1824. /* For vanguards, the server-side intro circ is not cannibalized
  1825. * because we pre-build 4 hop HS circuits, and it only needs a 3 hop
  1826. * circuit. It is also long-lived, so it is more important that
  1827. * it have lower latency than get built fast.
  1828. */
  1829. if (circuit_should_use_vanguards(purpose_to_build) &&
  1830. purpose_to_build == CIRCUIT_PURPOSE_S_ESTABLISH_INTRO) {
  1831. return 0;
  1832. }
  1833. return 1;
  1834. }
  1835. /** Launch a new circuit with purpose <b>purpose</b> and exit node
  1836. * <b>extend_info</b> (or NULL to select a random exit node). If flags
  1837. * contains CIRCLAUNCH_NEED_UPTIME, choose among routers with high uptime. If
  1838. * CIRCLAUNCH_NEED_CAPACITY is set, choose among routers with high bandwidth.
  1839. * If CIRCLAUNCH_IS_INTERNAL is true, the last hop need not be an exit node.
  1840. * If CIRCLAUNCH_ONEHOP_TUNNEL is set, the circuit will have only one hop.
  1841. * Return the newly allocated circuit on success, or NULL on failure. */
  1842. origin_circuit_t *
  1843. circuit_launch_by_extend_info(uint8_t purpose,
  1844. extend_info_t *extend_info,
  1845. int flags)
  1846. {
  1847. origin_circuit_t *circ;
  1848. int onehop_tunnel = (flags & CIRCLAUNCH_ONEHOP_TUNNEL) != 0;
  1849. int have_path = have_enough_path_info(! (flags & CIRCLAUNCH_IS_INTERNAL) );
  1850. /* Keep some stats about our attempts to launch HS rendezvous circuits */
  1851. if (purpose == CIRCUIT_PURPOSE_S_CONNECT_REND) {
  1852. hs_stats_note_service_rendezvous_launch();
  1853. }
  1854. if (!onehop_tunnel && (!router_have_minimum_dir_info() || !have_path)) {
  1855. log_debug(LD_CIRC,"Haven't %s yet; canceling "
  1856. "circuit launch.",
  1857. !router_have_minimum_dir_info() ?
  1858. "fetched enough directory info" :
  1859. "received a consensus with exits");
  1860. return NULL;
  1861. }
  1862. /* If we can/should cannibalize another circuit to build this one,
  1863. * then do so. */
  1864. if (circuit_should_cannibalize_to_build(purpose,
  1865. extend_info != NULL,
  1866. onehop_tunnel)) {
  1867. /* see if there are appropriate circs available to cannibalize. */
  1868. /* XXX if we're planning to add a hop, perhaps we want to look for
  1869. * internal circs rather than exit circs? -RD */
  1870. circ = circuit_find_to_cannibalize(purpose, extend_info, flags);
  1871. if (circ) {
  1872. uint8_t old_purpose = circ->base_.purpose;
  1873. struct timeval old_timestamp_began = circ->base_.timestamp_began;
  1874. log_info(LD_CIRC, "Cannibalizing circ %u (id: %" PRIu32 ") for "
  1875. "purpose %d (%s)",
  1876. TO_CIRCUIT(circ)->n_circ_id, circ->global_identifier, purpose,
  1877. circuit_purpose_to_string(purpose));
  1878. if ((purpose == CIRCUIT_PURPOSE_S_CONNECT_REND ||
  1879. purpose == CIRCUIT_PURPOSE_C_INTRODUCING) &&
  1880. circ->path_state == PATH_STATE_BUILD_SUCCEEDED) {
  1881. /* Path bias: Cannibalized rends pre-emptively count as a
  1882. * successfully built but unused closed circuit. We don't
  1883. * wait until the extend (or the close) because the rend
  1884. * point could be malicious.
  1885. *
  1886. * Same deal goes for client side introductions. Clients
  1887. * can be manipulated to connect repeatedly to them
  1888. * (especially web clients).
  1889. *
  1890. * If we decide to probe the initial portion of these circs,
  1891. * (up to the adversary's final hop), we need to remove this,
  1892. * or somehow mark the circuit with a special path state.
  1893. */
  1894. /* This must be called before the purpose change */
  1895. pathbias_check_close(circ, END_CIRC_REASON_FINISHED);
  1896. }
  1897. circuit_change_purpose(TO_CIRCUIT(circ), purpose);
  1898. /* Reset the start date of this circ, else expire_building
  1899. * will see it and think it's been trying to build since it
  1900. * began.
  1901. *
  1902. * Technically, the code should reset this when the
  1903. * create cell is finally sent, but we're close enough
  1904. * here. */
  1905. tor_gettimeofday(&circ->base_.timestamp_began);
  1906. control_event_circuit_cannibalized(circ, old_purpose,
  1907. &old_timestamp_began);
  1908. switch (purpose) {
  1909. case CIRCUIT_PURPOSE_C_ESTABLISH_REND:
  1910. /* it's ready right now */
  1911. break;
  1912. case CIRCUIT_PURPOSE_C_INTRODUCING:
  1913. case CIRCUIT_PURPOSE_S_CONNECT_REND:
  1914. case CIRCUIT_PURPOSE_C_GENERAL:
  1915. case CIRCUIT_PURPOSE_S_HSDIR_POST:
  1916. case CIRCUIT_PURPOSE_C_HSDIR_GET:
  1917. case CIRCUIT_PURPOSE_S_ESTABLISH_INTRO:
  1918. /* need to add a new hop */
  1919. tor_assert(extend_info);
  1920. if (circuit_extend_to_new_exit(circ, extend_info) < 0)
  1921. return NULL;
  1922. break;
  1923. default:
  1924. log_warn(LD_BUG,
  1925. "unexpected purpose %d when cannibalizing a circ.",
  1926. purpose);
  1927. tor_fragile_assert();
  1928. return NULL;
  1929. }
  1930. return circ;
  1931. }
  1932. }
  1933. if (did_circs_fail_last_period &&
  1934. n_circuit_failures > MAX_CIRCUIT_FAILURES) {
  1935. /* too many failed circs in a row. don't try. */
  1936. // log_fn(LOG_INFO,"%d failures so far, not trying.",n_circuit_failures);
  1937. return NULL;
  1938. }
  1939. /* try a circ. if it fails, circuit_mark_for_close will increment
  1940. * n_circuit_failures */
  1941. return circuit_establish_circuit(purpose, extend_info, flags);
  1942. }
  1943. /** Record another failure at opening a general circuit. When we have
  1944. * too many, we'll stop trying for the remainder of this minute.
  1945. */
  1946. static void
  1947. circuit_increment_failure_count(void)
  1948. {
  1949. ++n_circuit_failures;
  1950. log_debug(LD_CIRC,"n_circuit_failures now %d.",n_circuit_failures);
  1951. }
  1952. /** Reset the failure count for opening general circuits. This means
  1953. * we will try MAX_CIRCUIT_FAILURES times more (if necessary) before
  1954. * stopping again.
  1955. */
  1956. void
  1957. circuit_reset_failure_count(int timeout)
  1958. {
  1959. if (timeout && n_circuit_failures > MAX_CIRCUIT_FAILURES)
  1960. did_circs_fail_last_period = 1;
  1961. else
  1962. did_circs_fail_last_period = 0;
  1963. n_circuit_failures = 0;
  1964. }
  1965. /** Find an open circ that we're happy to use for <b>conn</b> and return 1. If
  1966. * there isn't one, and there isn't one on the way, launch one and return
  1967. * 0. If it will never work, return -1.
  1968. *
  1969. * Write the found or in-progress or launched circ into *circp.
  1970. */
  1971. static int
  1972. circuit_get_open_circ_or_launch(entry_connection_t *conn,
  1973. uint8_t desired_circuit_purpose,
  1974. origin_circuit_t **circp)
  1975. {
  1976. origin_circuit_t *circ;
  1977. int check_exit_policy;
  1978. int need_uptime, need_internal;
  1979. int want_onehop;
  1980. const or_options_t *options = get_options();
  1981. tor_assert(conn);
  1982. tor_assert(circp);
  1983. if (ENTRY_TO_CONN(conn)->state != AP_CONN_STATE_CIRCUIT_WAIT) {
  1984. connection_t *c = ENTRY_TO_CONN(conn);
  1985. log_err(LD_BUG, "Connection state mismatch: wanted "
  1986. "AP_CONN_STATE_CIRCUIT_WAIT, but got %d (%s)",
  1987. c->state, conn_state_to_string(c->type, c->state));
  1988. }
  1989. tor_assert(ENTRY_TO_CONN(conn)->state == AP_CONN_STATE_CIRCUIT_WAIT);
  1990. /* Will the exit policy of the exit node apply to this stream? */
  1991. check_exit_policy =
  1992. conn->socks_request->command == SOCKS_COMMAND_CONNECT &&
  1993. !conn->use_begindir &&
  1994. !connection_edge_is_rendezvous_stream(ENTRY_TO_EDGE_CONN(conn));
  1995. /* Does this connection want a one-hop circuit? */
  1996. want_onehop = conn->want_onehop;
  1997. /* Do we need a high-uptime circuit? */
  1998. need_uptime = !conn->want_onehop && !conn->use_begindir &&
  1999. smartlist_contains_int_as_string(options->LongLivedPorts,
  2000. conn->socks_request->port);
  2001. /* Do we need an "internal" circuit? */
  2002. if (desired_circuit_purpose != CIRCUIT_PURPOSE_C_GENERAL)
  2003. need_internal = 1;
  2004. else if (conn->use_begindir || conn->want_onehop)
  2005. need_internal = 1;
  2006. else
  2007. need_internal = 0;
  2008. /* We now know what kind of circuit we need. See if there is an
  2009. * open circuit that we can use for this stream */
  2010. circ = circuit_get_best(conn, 1 /* Insist on open circuits */,
  2011. desired_circuit_purpose,
  2012. need_uptime, need_internal);
  2013. if (circ) {
  2014. /* We got a circuit that will work for this stream! We can return it. */
  2015. *circp = circ;
  2016. return 1; /* we're happy */
  2017. }
  2018. /* Okay, there's no circuit open that will work for this stream. Let's
  2019. * see if there's an in-progress circuit or if we have to launch one */
  2020. /* Do we know enough directory info to build circuits at all? */
  2021. int have_path = have_enough_path_info(!need_internal);
  2022. if (!want_onehop && (!router_have_minimum_dir_info() || !have_path)) {
  2023. /* If we don't have enough directory information, we can't build
  2024. * multihop circuits.
  2025. */
  2026. if (!connection_get_by_type(CONN_TYPE_DIR)) {
  2027. int severity = LOG_NOTICE;
  2028. /* Retry some stuff that might help the connection work. */
  2029. /* If we are configured with EntryNodes or UseBridges */
  2030. if (entry_list_is_constrained(options)) {
  2031. /* Retry all our guards / bridges.
  2032. * guards_retry_optimistic() always returns true here. */
  2033. int rv = guards_retry_optimistic(options);
  2034. tor_assert_nonfatal_once(rv);
  2035. log_fn(severity, LD_APP|LD_DIR,
  2036. "Application request when we haven't %s. "
  2037. "Optimistically trying known %s again.",
  2038. !router_have_minimum_dir_info() ?
  2039. "used client functionality lately" :
  2040. "received a consensus with exits",
  2041. options->UseBridges ? "bridges" : "entrynodes");
  2042. } else {
  2043. /* Getting directory documents doesn't help much if we have a limited
  2044. * number of guards */
  2045. tor_assert_nonfatal(!options->UseBridges);
  2046. tor_assert_nonfatal(!options->EntryNodes);
  2047. /* Retry our directory fetches, so we have a fresh set of guard info */
  2048. log_fn(severity, LD_APP|LD_DIR,
  2049. "Application request when we haven't %s. "
  2050. "Optimistically trying directory fetches again.",
  2051. !router_have_minimum_dir_info() ?
  2052. "used client functionality lately" :
  2053. "received a consensus with exits");
  2054. routerlist_retry_directory_downloads(time(NULL));
  2055. }
  2056. }
  2057. /* Since we didn't have enough directory info, we can't attach now. The
  2058. * stream will be dealt with when router_have_minimum_dir_info becomes 1,
  2059. * or when all directory attempts fail and directory_all_unreachable()
  2060. * kills it.
  2061. */
  2062. return 0;
  2063. }
  2064. /* Check whether the exit policy of the chosen exit, or the exit policies
  2065. * of _all_ nodes, would forbid this node. */
  2066. if (check_exit_policy) {
  2067. if (!conn->chosen_exit_name) {
  2068. struct in_addr in;
  2069. tor_addr_t addr, *addrp=NULL;
  2070. if (tor_inet_aton(conn->socks_request->address, &in)) {
  2071. tor_addr_from_in(&addr, &in);
  2072. addrp = &addr;
  2073. }
  2074. if (router_exit_policy_all_nodes_reject(addrp,
  2075. conn->socks_request->port,
  2076. need_uptime)) {
  2077. log_notice(LD_APP,
  2078. "No Tor server allows exit to %s:%d. Rejecting.",
  2079. safe_str_client(conn->socks_request->address),
  2080. conn->socks_request->port);
  2081. return -1;
  2082. }
  2083. } else {
  2084. /* XXXX Duplicates checks in connection_ap_handshake_attach_circuit:
  2085. * refactor into a single function. */
  2086. const node_t *node = node_get_by_nickname(conn->chosen_exit_name, 0);
  2087. int opt = conn->chosen_exit_optional;
  2088. if (node && !connection_ap_can_use_exit(conn, node)) {
  2089. log_fn(opt ? LOG_INFO : LOG_WARN, LD_APP,
  2090. "Requested exit point '%s' is excluded or "
  2091. "would refuse request. %s.",
  2092. conn->chosen_exit_name, opt ? "Trying others" : "Closing");
  2093. if (opt) {
  2094. conn->chosen_exit_optional = 0;
  2095. tor_free(conn->chosen_exit_name);
  2096. /* Try again. */
  2097. return circuit_get_open_circ_or_launch(conn,
  2098. desired_circuit_purpose,
  2099. circp);
  2100. }
  2101. return -1;
  2102. }
  2103. }
  2104. }
  2105. /* Now, check whether there already a circuit on the way that could handle
  2106. * this stream. This check matches the one above, but this time we
  2107. * do not require that the circuit will work. */
  2108. circ = circuit_get_best(conn, 0 /* don't insist on open circuits */,
  2109. desired_circuit_purpose,
  2110. need_uptime, need_internal);
  2111. if (circ)
  2112. log_debug(LD_CIRC, "one on the way!");
  2113. if (!circ) {
  2114. /* No open or in-progress circuit could handle this stream! We
  2115. * will have to launch one!
  2116. */
  2117. /* The chosen exit node, if there is one. */
  2118. extend_info_t *extend_info=NULL;
  2119. const int n_pending = count_pending_general_client_circuits();
  2120. /* Do we have too many pending circuits? */
  2121. if (n_pending >= options->MaxClientCircuitsPending) {
  2122. static ratelim_t delay_limit = RATELIM_INIT(10*60);
  2123. char *m;
  2124. if ((m = rate_limit_log(&delay_limit, approx_time()))) {
  2125. log_notice(LD_APP, "We'd like to launch a circuit to handle a "
  2126. "connection, but we already have %d general-purpose client "
  2127. "circuits pending. Waiting until some finish.%s",
  2128. n_pending, m);
  2129. tor_free(m);
  2130. }
  2131. return 0;
  2132. }
  2133. /* If this is a hidden service trying to start an introduction point,
  2134. * handle that case. */
  2135. if (desired_circuit_purpose == CIRCUIT_PURPOSE_C_INTRODUCE_ACK_WAIT) {
  2136. const edge_connection_t *edge_conn = ENTRY_TO_EDGE_CONN(conn);
  2137. /* need to pick an intro point */
  2138. extend_info = hs_client_get_random_intro_from_edge(edge_conn);
  2139. if (!extend_info) {
  2140. log_info(LD_REND, "No intro points: re-fetching service descriptor.");
  2141. if (edge_conn->rend_data) {
  2142. rend_client_refetch_v2_renddesc(edge_conn->rend_data);
  2143. } else {
  2144. hs_client_refetch_hsdesc(&edge_conn->hs_ident->identity_pk);
  2145. }
  2146. connection_ap_mark_as_non_pending_circuit(conn);
  2147. ENTRY_TO_CONN(conn)->state = AP_CONN_STATE_RENDDESC_WAIT;
  2148. return 0;
  2149. }
  2150. log_info(LD_REND,"Chose %s as intro point for '%s'.",
  2151. extend_info_describe(extend_info),
  2152. (edge_conn->rend_data) ?
  2153. safe_str_client(rend_data_get_address(edge_conn->rend_data)) :
  2154. "service");
  2155. }
  2156. /* If we have specified a particular exit node for our
  2157. * connection, then be sure to open a circuit to that exit node.
  2158. */
  2159. if (desired_circuit_purpose == CIRCUIT_PURPOSE_C_GENERAL ||
  2160. desired_circuit_purpose == CIRCUIT_PURPOSE_S_HSDIR_POST ||
  2161. desired_circuit_purpose == CIRCUIT_PURPOSE_C_HSDIR_GET) {
  2162. if (conn->chosen_exit_name) {
  2163. const node_t *r;
  2164. int opt = conn->chosen_exit_optional;
  2165. r = node_get_by_nickname(conn->chosen_exit_name, 0);
  2166. if (r && node_has_preferred_descriptor(r, conn->want_onehop ? 1 : 0)) {
  2167. /* We might want to connect to an IPv6 bridge for loading
  2168. descriptors so we use the preferred address rather than
  2169. the primary. */
  2170. extend_info = extend_info_from_node(r, conn->want_onehop ? 1 : 0);
  2171. if (!extend_info) {
  2172. log_warn(LD_CIRC,"Could not make a one-hop connection to %s. "
  2173. "Discarding this circuit.", conn->chosen_exit_name);
  2174. return -1;
  2175. }
  2176. } else { /* ! (r && node_has_preferred_descriptor(...)) */
  2177. log_debug(LD_DIR, "considering %d, %s",
  2178. want_onehop, conn->chosen_exit_name);
  2179. if (want_onehop && conn->chosen_exit_name[0] == '$') {
  2180. /* We're asking for a one-hop circuit to a router that
  2181. * we don't have a routerinfo about. Make up an extend_info. */
  2182. /* XXX prop220: we need to make chosen_exit_name able to
  2183. * encode both key formats. This is not absolutely critical
  2184. * since this is just for one-hop circuits, but we should
  2185. * still get it done */
  2186. char digest[DIGEST_LEN];
  2187. char *hexdigest = conn->chosen_exit_name+1;
  2188. tor_addr_t addr;
  2189. if (strlen(hexdigest) < HEX_DIGEST_LEN ||
  2190. base16_decode(digest,DIGEST_LEN,
  2191. hexdigest,HEX_DIGEST_LEN) != DIGEST_LEN) {
  2192. log_info(LD_DIR, "Broken exit digest on tunnel conn. Closing.");
  2193. return -1;
  2194. }
  2195. if (tor_addr_parse(&addr, conn->socks_request->address) < 0) {
  2196. log_info(LD_DIR, "Broken address %s on tunnel conn. Closing.",
  2197. escaped_safe_str_client(conn->socks_request->address));
  2198. return -1;
  2199. }
  2200. /* XXXX prop220 add a workaround for ed25519 ID below*/
  2201. extend_info = extend_info_new(conn->chosen_exit_name+1,
  2202. digest,
  2203. NULL, /* Ed25519 ID */
  2204. NULL, NULL, /* onion keys */
  2205. &addr, conn->socks_request->port);
  2206. } else { /* ! (want_onehop && conn->chosen_exit_name[0] == '$') */
  2207. /* We will need an onion key for the router, and we
  2208. * don't have one. Refuse or relax requirements. */
  2209. log_fn(opt ? LOG_INFO : LOG_WARN, LD_APP,
  2210. "Requested exit point '%s' is not known. %s.",
  2211. conn->chosen_exit_name, opt ? "Trying others" : "Closing");
  2212. if (opt) {
  2213. conn->chosen_exit_optional = 0;
  2214. tor_free(conn->chosen_exit_name);
  2215. /* Try again with no requested exit */
  2216. return circuit_get_open_circ_or_launch(conn,
  2217. desired_circuit_purpose,
  2218. circp);
  2219. }
  2220. return -1;
  2221. }
  2222. }
  2223. }
  2224. } /* Done checking for general circutis with chosen exits. */
  2225. /* What purpose do we need to launch this circuit with? */
  2226. uint8_t new_circ_purpose;
  2227. if (desired_circuit_purpose == CIRCUIT_PURPOSE_C_REND_JOINED)
  2228. new_circ_purpose = CIRCUIT_PURPOSE_C_ESTABLISH_REND;
  2229. else if (desired_circuit_purpose == CIRCUIT_PURPOSE_C_INTRODUCE_ACK_WAIT)
  2230. new_circ_purpose = CIRCUIT_PURPOSE_C_INTRODUCING;
  2231. else
  2232. new_circ_purpose = desired_circuit_purpose;
  2233. /* Determine what kind of a circuit to launch, and actually launch it. */
  2234. {
  2235. int flags = CIRCLAUNCH_NEED_CAPACITY;
  2236. if (want_onehop) flags |= CIRCLAUNCH_ONEHOP_TUNNEL;
  2237. if (need_uptime) flags |= CIRCLAUNCH_NEED_UPTIME;
  2238. if (need_internal) flags |= CIRCLAUNCH_IS_INTERNAL;
  2239. /* If we are about to pick a v3 RP right now, make sure we pick a
  2240. * rendezvous point that supports the v3 protocol! */
  2241. if (desired_circuit_purpose == CIRCUIT_PURPOSE_C_REND_JOINED &&
  2242. new_circ_purpose == CIRCUIT_PURPOSE_C_ESTABLISH_REND &&
  2243. ENTRY_TO_EDGE_CONN(conn)->hs_ident) {
  2244. flags |= CIRCLAUNCH_IS_V3_RP;
  2245. log_info(LD_GENERAL, "Getting rendezvous circuit to v3 service!");
  2246. }
  2247. circ = circuit_launch_by_extend_info(new_circ_purpose, extend_info,
  2248. flags);
  2249. }
  2250. extend_info_free(extend_info);
  2251. /* Now trigger things that need to happen when we launch circuits */
  2252. if (desired_circuit_purpose == CIRCUIT_PURPOSE_C_GENERAL ||
  2253. desired_circuit_purpose == CIRCUIT_PURPOSE_C_HSDIR_GET ||
  2254. desired_circuit_purpose == CIRCUIT_PURPOSE_S_HSDIR_POST) {
  2255. /* We just caused a circuit to get built because of this stream.
  2256. * If this stream has caused a _lot_ of circuits to be built, that's
  2257. * a bad sign: we should tell the user. */
  2258. if (conn->num_circuits_launched < NUM_CIRCUITS_LAUNCHED_THRESHOLD &&
  2259. ++conn->num_circuits_launched == NUM_CIRCUITS_LAUNCHED_THRESHOLD)
  2260. log_info(LD_CIRC, "The application request to %s:%d has launched "
  2261. "%d circuits without finding one it likes.",
  2262. escaped_safe_str_client(conn->socks_request->address),
  2263. conn->socks_request->port,
  2264. conn->num_circuits_launched);
  2265. } else {
  2266. /* help predict this next time */
  2267. rep_hist_note_used_internal(time(NULL), need_uptime, 1);
  2268. if (circ) {
  2269. const edge_connection_t *edge_conn = ENTRY_TO_EDGE_CONN(conn);
  2270. if (edge_conn->rend_data) {
  2271. /* write the service_id into circ */
  2272. circ->rend_data = rend_data_dup(edge_conn->rend_data);
  2273. } else if (edge_conn->hs_ident) {
  2274. circ->hs_ident =
  2275. hs_ident_circuit_new(&edge_conn->hs_ident->identity_pk,
  2276. HS_IDENT_CIRCUIT_INTRO);
  2277. }
  2278. if (circ->base_.purpose == CIRCUIT_PURPOSE_C_ESTABLISH_REND &&
  2279. circ->base_.state == CIRCUIT_STATE_OPEN)
  2280. circuit_has_opened(circ);
  2281. }
  2282. }
  2283. } /* endif (!circ) */
  2284. /* We either found a good circuit, or launched a new circuit, or failed to
  2285. * do so. Report success, and delay. */
  2286. if (circ) {
  2287. /* Mark the circuit with the isolation fields for this connection.
  2288. * When the circuit arrives, we'll clear these flags: this is
  2289. * just some internal bookkeeping to make sure that we have
  2290. * launched enough circuits.
  2291. */
  2292. connection_edge_update_circuit_isolation(conn, circ, 0);
  2293. } else {
  2294. log_info(LD_APP,
  2295. "No safe circuit (purpose %d) ready for edge "
  2296. "connection; delaying.",
  2297. desired_circuit_purpose);
  2298. }
  2299. *circp = circ;
  2300. return 0;
  2301. }
  2302. /** Return true iff <b>crypt_path</b> is one of the crypt_paths for
  2303. * <b>circ</b>. */
  2304. static int
  2305. cpath_is_on_circuit(origin_circuit_t *circ, crypt_path_t *crypt_path)
  2306. {
  2307. crypt_path_t *cpath, *cpath_next = NULL;
  2308. for (cpath = circ->cpath; cpath_next != circ->cpath; cpath = cpath_next) {
  2309. cpath_next = cpath->next;
  2310. if (crypt_path == cpath)
  2311. return 1;
  2312. }
  2313. return 0;
  2314. }
  2315. /** Return true iff client-side optimistic data is supported. */
  2316. static int
  2317. optimistic_data_enabled(void)
  2318. {
  2319. const or_options_t *options = get_options();
  2320. if (options->OptimisticData < 0) {
  2321. /* Note: this default was 0 before #18815 was merged. We can't take the
  2322. * parameter out of the consensus until versions before that are all
  2323. * obsolete. */
  2324. const int32_t enabled =
  2325. networkstatus_get_param(NULL, "UseOptimisticData", /*default*/ 1, 0, 1);
  2326. return (int)enabled;
  2327. }
  2328. return options->OptimisticData;
  2329. }
  2330. /** Attach the AP stream <b>apconn</b> to circ's linked list of
  2331. * p_streams. Also set apconn's cpath_layer to <b>cpath</b>, or to the last
  2332. * hop in circ's cpath if <b>cpath</b> is NULL.
  2333. */
  2334. static void
  2335. link_apconn_to_circ(entry_connection_t *apconn, origin_circuit_t *circ,
  2336. crypt_path_t *cpath)
  2337. {
  2338. const node_t *exitnode = NULL;
  2339. /* add it into the linked list of streams on this circuit */
  2340. log_debug(LD_APP|LD_CIRC, "attaching new conn to circ. n_circ_id %u.",
  2341. (unsigned)circ->base_.n_circ_id);
  2342. /* reset it, so we can measure circ timeouts */
  2343. ENTRY_TO_CONN(apconn)->timestamp_last_read_allowed = time(NULL);
  2344. ENTRY_TO_EDGE_CONN(apconn)->next_stream = circ->p_streams;
  2345. ENTRY_TO_EDGE_CONN(apconn)->on_circuit = TO_CIRCUIT(circ);
  2346. /* assert_connection_ok(conn, time(NULL)); */
  2347. circ->p_streams = ENTRY_TO_EDGE_CONN(apconn);
  2348. if (connection_edge_is_rendezvous_stream(ENTRY_TO_EDGE_CONN(apconn))) {
  2349. /* We are attaching a stream to a rendezvous circuit. That means
  2350. * that an attempt to connect to a hidden service just
  2351. * succeeded. Tell rendclient.c. */
  2352. hs_client_note_connection_attempt_succeeded(ENTRY_TO_EDGE_CONN(apconn));
  2353. }
  2354. if (cpath) { /* we were given one; use it */
  2355. tor_assert(cpath_is_on_circuit(circ, cpath));
  2356. } else {
  2357. /* use the last hop in the circuit */
  2358. tor_assert(circ->cpath);
  2359. tor_assert(circ->cpath->prev);
  2360. tor_assert(circ->cpath->prev->state == CPATH_STATE_OPEN);
  2361. cpath = circ->cpath->prev;
  2362. }
  2363. ENTRY_TO_EDGE_CONN(apconn)->cpath_layer = cpath;
  2364. circ->isolation_any_streams_attached = 1;
  2365. connection_edge_update_circuit_isolation(apconn, circ, 0);
  2366. /* Compute the exitnode if possible, for logging below */
  2367. if (cpath->extend_info)
  2368. exitnode = node_get_by_id(cpath->extend_info->identity_digest);
  2369. /* See if we can use optimistic data on this circuit */
  2370. if (optimistic_data_enabled() &&
  2371. (circ->base_.purpose == CIRCUIT_PURPOSE_C_GENERAL ||
  2372. circ->base_.purpose == CIRCUIT_PURPOSE_C_HSDIR_GET ||
  2373. circ->base_.purpose == CIRCUIT_PURPOSE_S_HSDIR_POST ||
  2374. circ->base_.purpose == CIRCUIT_PURPOSE_C_REND_JOINED))
  2375. apconn->may_use_optimistic_data = 1;
  2376. else
  2377. apconn->may_use_optimistic_data = 0;
  2378. log_info(LD_APP, "Looks like completed circuit to %s %s allow "
  2379. "optimistic data for connection to %s",
  2380. circ->base_.purpose == CIRCUIT_PURPOSE_C_GENERAL ?
  2381. /* node_describe() does the right thing if exitnode is NULL */
  2382. safe_str_client(node_describe(exitnode)) :
  2383. "hidden service",
  2384. apconn->may_use_optimistic_data ? "does" : "doesn't",
  2385. safe_str_client(apconn->socks_request->address));
  2386. }
  2387. /** Return true iff <b>address</b> is matched by one of the entries in
  2388. * TrackHostExits. */
  2389. int
  2390. hostname_in_track_host_exits(const or_options_t *options, const char *address)
  2391. {
  2392. if (!options->TrackHostExits)
  2393. return 0;
  2394. SMARTLIST_FOREACH_BEGIN(options->TrackHostExits, const char *, cp) {
  2395. if (cp[0] == '.') { /* match end */
  2396. if (cp[1] == '\0' ||
  2397. !strcasecmpend(address, cp) ||
  2398. !strcasecmp(address, &cp[1]))
  2399. return 1;
  2400. } else if (strcasecmp(cp, address) == 0) {
  2401. return 1;
  2402. }
  2403. } SMARTLIST_FOREACH_END(cp);
  2404. return 0;
  2405. }
  2406. /** If an exit wasn't explicitly specified for <b>conn</b>, consider saving
  2407. * the exit that we *did* choose for use by future connections to
  2408. * <b>conn</b>'s destination.
  2409. */
  2410. static void
  2411. consider_recording_trackhost(const entry_connection_t *conn,
  2412. const origin_circuit_t *circ)
  2413. {
  2414. const or_options_t *options = get_options();
  2415. char *new_address = NULL;
  2416. char fp[HEX_DIGEST_LEN+1];
  2417. /* Search the addressmap for this conn's destination. */
  2418. /* If they're not in the address map.. */
  2419. if (!options->TrackHostExits ||
  2420. addressmap_have_mapping(conn->socks_request->address,
  2421. options->TrackHostExitsExpire))
  2422. return; /* nothing to track, or already mapped */
  2423. if (!hostname_in_track_host_exits(options, conn->socks_request->address) ||
  2424. !circ->build_state->chosen_exit)
  2425. return;
  2426. /* write down the fingerprint of the chosen exit, not the nickname,
  2427. * because the chosen exit might not be named. */
  2428. base16_encode(fp, sizeof(fp),
  2429. circ->build_state->chosen_exit->identity_digest, DIGEST_LEN);
  2430. /* Add this exit/hostname pair to the addressmap. */
  2431. tor_asprintf(&new_address, "%s.%s.exit",
  2432. conn->socks_request->address, fp);
  2433. addressmap_register(conn->socks_request->address, new_address,
  2434. time(NULL) + options->TrackHostExitsExpire,
  2435. ADDRMAPSRC_TRACKEXIT, 0, 0);
  2436. }
  2437. /** Attempt to attach the connection <b>conn</b> to <b>circ</b>, and send a
  2438. * begin or resolve cell as appropriate. Return values are as for
  2439. * connection_ap_handshake_attach_circuit. The stream will exit from the hop
  2440. * indicated by <b>cpath</b>, or from the last hop in circ's cpath if
  2441. * <b>cpath</b> is NULL. */
  2442. int
  2443. connection_ap_handshake_attach_chosen_circuit(entry_connection_t *conn,
  2444. origin_circuit_t *circ,
  2445. crypt_path_t *cpath)
  2446. {
  2447. connection_t *base_conn = ENTRY_TO_CONN(conn);
  2448. tor_assert(conn);
  2449. tor_assert(base_conn->state == AP_CONN_STATE_CIRCUIT_WAIT ||
  2450. base_conn->state == AP_CONN_STATE_CONTROLLER_WAIT);
  2451. tor_assert(conn->socks_request);
  2452. tor_assert(circ);
  2453. tor_assert(circ->base_.state == CIRCUIT_STATE_OPEN);
  2454. base_conn->state = AP_CONN_STATE_CIRCUIT_WAIT;
  2455. if (!circ->base_.timestamp_dirty ||
  2456. ((conn->entry_cfg.isolation_flags & ISO_SOCKSAUTH) &&
  2457. (conn->entry_cfg.socks_iso_keep_alive) &&
  2458. (conn->socks_request->usernamelen ||
  2459. conn->socks_request->passwordlen))) {
  2460. /* When stream isolation is in use and controlled by an application
  2461. * we are willing to keep using the stream. */
  2462. circ->base_.timestamp_dirty = approx_time();
  2463. }
  2464. pathbias_count_use_attempt(circ);
  2465. /* Now, actually link the connection. */
  2466. link_apconn_to_circ(conn, circ, cpath);
  2467. tor_assert(conn->socks_request);
  2468. if (conn->socks_request->command == SOCKS_COMMAND_CONNECT) {
  2469. if (!conn->use_begindir)
  2470. consider_recording_trackhost(conn, circ);
  2471. if (connection_ap_handshake_send_begin(conn) < 0)
  2472. return -1;
  2473. } else {
  2474. if (connection_ap_handshake_send_resolve(conn) < 0)
  2475. return -1;
  2476. }
  2477. return 1;
  2478. }
  2479. /**
  2480. * Return an appropriate circuit purpose for non-rend streams.
  2481. * We don't handle rends here because a rend stream triggers two
  2482. * circuit builds with different purposes, so it is handled elsewhere.
  2483. *
  2484. * This function just figures out what type of hsdir activity this is,
  2485. * and tells us. Everything else is general.
  2486. */
  2487. static int
  2488. connection_ap_get_nonrend_circ_purpose(const entry_connection_t *conn)
  2489. {
  2490. const connection_t *base_conn = ENTRY_TO_CONN(conn);
  2491. tor_assert_nonfatal(!connection_edge_is_rendezvous_stream(
  2492. ENTRY_TO_EDGE_CONN(conn)));
  2493. if (base_conn->linked_conn &&
  2494. base_conn->linked_conn->type == CONN_TYPE_DIR) {
  2495. /* Set a custom purpose for hsdir activity */
  2496. if (base_conn->linked_conn->purpose == DIR_PURPOSE_UPLOAD_RENDDESC_V2 ||
  2497. base_conn->linked_conn->purpose == DIR_PURPOSE_UPLOAD_HSDESC) {
  2498. return CIRCUIT_PURPOSE_S_HSDIR_POST;
  2499. } else if (base_conn->linked_conn->purpose
  2500. == DIR_PURPOSE_FETCH_RENDDESC_V2 ||
  2501. base_conn->linked_conn->purpose
  2502. == DIR_PURPOSE_FETCH_HSDESC) {
  2503. return CIRCUIT_PURPOSE_C_HSDIR_GET;
  2504. }
  2505. }
  2506. /* All other purposes are general for now */
  2507. return CIRCUIT_PURPOSE_C_GENERAL;
  2508. }
  2509. /** Try to find a safe live circuit for stream <b>conn</b>. If we find one,
  2510. * attach the stream, send appropriate cells, and return 1. Otherwise,
  2511. * try to launch new circuit(s) for the stream. If we can launch
  2512. * circuits, return 0. Otherwise, if we simply can't proceed with
  2513. * this stream, return -1. (conn needs to die, and is maybe already marked).
  2514. */
  2515. /* XXXX this function should mark for close whenever it returns -1;
  2516. * its callers shouldn't have to worry about that. */
  2517. int
  2518. connection_ap_handshake_attach_circuit(entry_connection_t *conn)
  2519. {
  2520. connection_t *base_conn = ENTRY_TO_CONN(conn);
  2521. int retval;
  2522. int conn_age;
  2523. int want_onehop;
  2524. tor_assert(conn);
  2525. tor_assert(base_conn->state == AP_CONN_STATE_CIRCUIT_WAIT);
  2526. tor_assert(conn->socks_request);
  2527. want_onehop = conn->want_onehop;
  2528. conn_age = (int)(time(NULL) - base_conn->timestamp_created);
  2529. /* Is this connection so old that we should give up on it? */
  2530. if (conn_age >= get_options()->SocksTimeout) {
  2531. int severity = (tor_addr_is_null(&base_conn->addr) && !base_conn->port) ?
  2532. LOG_INFO : LOG_NOTICE;
  2533. log_fn(severity, LD_APP,
  2534. "Tried for %d seconds to get a connection to %s:%d. Giving up.",
  2535. conn_age, safe_str_client(conn->socks_request->address),
  2536. conn->socks_request->port);
  2537. return -1;
  2538. }
  2539. /* We handle "general" (non-onion) connections much more straightforwardly.
  2540. */
  2541. if (!connection_edge_is_rendezvous_stream(ENTRY_TO_EDGE_CONN(conn))) {
  2542. /* we're a general conn */
  2543. origin_circuit_t *circ=NULL;
  2544. /* Are we linked to a dir conn that aims to fetch a consensus?
  2545. * We check here because the conn might no longer be needed. */
  2546. if (base_conn->linked_conn &&
  2547. base_conn->linked_conn->type == CONN_TYPE_DIR &&
  2548. base_conn->linked_conn->purpose == DIR_PURPOSE_FETCH_CONSENSUS) {
  2549. /* Yes we are. Is there a consensus fetch farther along than us? */
  2550. if (networkstatus_consensus_is_already_downloading(
  2551. TO_DIR_CONN(base_conn->linked_conn)->requested_resource)) {
  2552. /* We're doing the "multiple consensus fetch attempts" game from
  2553. * proposal 210, and we're late to the party. Just close this conn.
  2554. * The circuit and TLS conn that we made will time out after a while
  2555. * if nothing else wants to use them. */
  2556. log_info(LD_DIR, "Closing extra consensus fetch (to %s) since one "
  2557. "is already downloading.", base_conn->linked_conn->address);
  2558. return -1;
  2559. }
  2560. }
  2561. /* If we have a chosen exit, we need to use a circuit that's
  2562. * open to that exit. See what exit we meant, and whether we can use it.
  2563. */
  2564. if (conn->chosen_exit_name) {
  2565. const node_t *node = node_get_by_nickname(conn->chosen_exit_name, 0);
  2566. int opt = conn->chosen_exit_optional;
  2567. if (!node && !want_onehop) {
  2568. /* We ran into this warning when trying to extend a circuit to a
  2569. * hidden service directory for which we didn't have a router
  2570. * descriptor. See flyspray task 767 for more details. We should
  2571. * keep this in mind when deciding to use BEGIN_DIR cells for other
  2572. * directory requests as well. -KL*/
  2573. log_fn(opt ? LOG_INFO : LOG_WARN, LD_APP,
  2574. "Requested exit point '%s' is not known. %s.",
  2575. conn->chosen_exit_name, opt ? "Trying others" : "Closing");
  2576. if (opt) {
  2577. /* If we are allowed to ignore the .exit request, do so */
  2578. conn->chosen_exit_optional = 0;
  2579. tor_free(conn->chosen_exit_name);
  2580. return 0;
  2581. }
  2582. return -1;
  2583. }
  2584. if (node && !connection_ap_can_use_exit(conn, node)) {
  2585. log_fn(opt ? LOG_INFO : LOG_WARN, LD_APP,
  2586. "Requested exit point '%s' is excluded or "
  2587. "would refuse request. %s.",
  2588. conn->chosen_exit_name, opt ? "Trying others" : "Closing");
  2589. if (opt) {
  2590. /* If we are allowed to ignore the .exit request, do so */
  2591. conn->chosen_exit_optional = 0;
  2592. tor_free(conn->chosen_exit_name);
  2593. return 0;
  2594. }
  2595. return -1;
  2596. }
  2597. }
  2598. /* Find the circuit that we should use, if there is one. Otherwise
  2599. * launch it
  2600. */
  2601. retval = circuit_get_open_circ_or_launch(conn,
  2602. connection_ap_get_nonrend_circ_purpose(conn),
  2603. &circ);
  2604. if (retval < 1) {
  2605. /* We were either told "-1" (complete failure) or 0 (circuit in
  2606. * progress); we can't attach this stream yet. */
  2607. return retval;
  2608. }
  2609. log_debug(LD_APP|LD_CIRC,
  2610. "Attaching apconn to circ %u (stream %d sec old).",
  2611. (unsigned)circ->base_.n_circ_id, conn_age);
  2612. /* print the circ's path, so clients can figure out which circs are
  2613. * sucking. */
  2614. circuit_log_path(LOG_INFO,LD_APP|LD_CIRC,circ);
  2615. /* We have found a suitable circuit for our conn. Hurray. Do
  2616. * the attachment. */
  2617. return connection_ap_handshake_attach_chosen_circuit(conn, circ, NULL);
  2618. } else { /* we're a rendezvous conn */
  2619. origin_circuit_t *rendcirc=NULL, *introcirc=NULL;
  2620. tor_assert(!ENTRY_TO_EDGE_CONN(conn)->cpath_layer);
  2621. /* start by finding a rendezvous circuit for us */
  2622. retval = circuit_get_open_circ_or_launch(
  2623. conn, CIRCUIT_PURPOSE_C_REND_JOINED, &rendcirc);
  2624. if (retval < 0) return -1; /* failed */
  2625. if (retval > 0) {
  2626. tor_assert(rendcirc);
  2627. /* one is already established, attach */
  2628. log_info(LD_REND,
  2629. "rend joined circ %u (id: %" PRIu32 ") already here. "
  2630. "Attaching. (stream %d sec old)",
  2631. (unsigned) TO_CIRCUIT(rendcirc)->n_circ_id,
  2632. rendcirc->global_identifier, conn_age);
  2633. /* Mark rendezvous circuits as 'newly dirty' every time you use
  2634. * them, since the process of rebuilding a rendezvous circ is so
  2635. * expensive. There is a tradeoff between linkability and
  2636. * feasibility, at this point.
  2637. */
  2638. rendcirc->base_.timestamp_dirty = time(NULL);
  2639. /* We've also attempted to use them. If they fail, we need to
  2640. * probe them for path bias */
  2641. pathbias_count_use_attempt(rendcirc);
  2642. link_apconn_to_circ(conn, rendcirc, NULL);
  2643. if (connection_ap_handshake_send_begin(conn) < 0)
  2644. return 0; /* already marked, let them fade away */
  2645. return 1;
  2646. }
  2647. /* At this point we need to re-check the state, since it's possible that
  2648. * our call to circuit_get_open_circ_or_launch() changed the connection's
  2649. * state from "CIRCUIT_WAIT" to "RENDDESC_WAIT" because we decided to
  2650. * re-fetch the descriptor.
  2651. */
  2652. if (ENTRY_TO_CONN(conn)->state != AP_CONN_STATE_CIRCUIT_WAIT) {
  2653. log_info(LD_REND, "This connection is no longer ready to attach; its "
  2654. "state changed."
  2655. "(We probably have to re-fetch its descriptor.)");
  2656. return 0;
  2657. }
  2658. if (rendcirc && (rendcirc->base_.purpose ==
  2659. CIRCUIT_PURPOSE_C_REND_READY_INTRO_ACKED)) {
  2660. log_info(LD_REND,
  2661. "pending-join circ %u (id: %" PRIu32 ") already here, with "
  2662. "intro ack. Stalling. (stream %d sec old)",
  2663. (unsigned) TO_CIRCUIT(rendcirc)->n_circ_id,
  2664. rendcirc->global_identifier, conn_age);
  2665. return 0;
  2666. }
  2667. /* it's on its way. find an intro circ. */
  2668. retval = circuit_get_open_circ_or_launch(
  2669. conn, CIRCUIT_PURPOSE_C_INTRODUCE_ACK_WAIT, &introcirc);
  2670. if (retval < 0) return -1; /* failed */
  2671. if (retval > 0) {
  2672. /* one has already sent the intro. keep waiting. */
  2673. tor_assert(introcirc);
  2674. log_info(LD_REND, "Intro circ %u (id: %" PRIu32 ") present and "
  2675. "awaiting ACK. Rend circuit %u (id: %" PRIu32 "). "
  2676. "Stalling. (stream %d sec old)",
  2677. (unsigned) TO_CIRCUIT(introcirc)->n_circ_id,
  2678. introcirc->global_identifier,
  2679. rendcirc ? (unsigned) TO_CIRCUIT(rendcirc)->n_circ_id : 0,
  2680. rendcirc ? rendcirc->global_identifier : 0,
  2681. conn_age);
  2682. return 0;
  2683. }
  2684. /* now rendcirc and introcirc are each either undefined or not finished */
  2685. if (rendcirc && introcirc &&
  2686. rendcirc->base_.purpose == CIRCUIT_PURPOSE_C_REND_READY) {
  2687. log_info(LD_REND,
  2688. "ready rend circ %u (id: %" PRIu32 ") already here. No"
  2689. "intro-ack yet on intro %u (id: %" PRIu32 "). "
  2690. "(stream %d sec old)",
  2691. (unsigned) TO_CIRCUIT(rendcirc)->n_circ_id,
  2692. rendcirc->global_identifier,
  2693. (unsigned) TO_CIRCUIT(introcirc)->n_circ_id,
  2694. introcirc->global_identifier, conn_age);
  2695. tor_assert(introcirc->base_.purpose == CIRCUIT_PURPOSE_C_INTRODUCING);
  2696. if (introcirc->base_.state == CIRCUIT_STATE_OPEN) {
  2697. int ret;
  2698. log_info(LD_REND, "Found open intro circ %u (id: %" PRIu32 "). "
  2699. "Rend circuit %u (id: %" PRIu32 "); Sending "
  2700. "introduction. (stream %d sec old)",
  2701. (unsigned) TO_CIRCUIT(introcirc)->n_circ_id,
  2702. introcirc->global_identifier,
  2703. (unsigned) TO_CIRCUIT(rendcirc)->n_circ_id,
  2704. rendcirc->global_identifier, conn_age);
  2705. ret = hs_client_send_introduce1(introcirc, rendcirc);
  2706. switch (ret) {
  2707. case 0: /* success */
  2708. rendcirc->base_.timestamp_dirty = time(NULL);
  2709. introcirc->base_.timestamp_dirty = time(NULL);
  2710. pathbias_count_use_attempt(introcirc);
  2711. pathbias_count_use_attempt(rendcirc);
  2712. assert_circuit_ok(TO_CIRCUIT(rendcirc));
  2713. assert_circuit_ok(TO_CIRCUIT(introcirc));
  2714. return 0;
  2715. case -1: /* transient error */
  2716. return 0;
  2717. case -2: /* permanent error */
  2718. return -1;
  2719. default: /* oops */
  2720. tor_fragile_assert();
  2721. return -1;
  2722. }
  2723. }
  2724. }
  2725. log_info(LD_REND, "Intro %u (id: %" PRIu32 ") and rend circuit %u "
  2726. "(id: %" PRIu32 ") circuits are not both ready. "
  2727. "Stalling conn. (%d sec old)",
  2728. introcirc ? (unsigned) TO_CIRCUIT(introcirc)->n_circ_id : 0,
  2729. introcirc ? introcirc->global_identifier : 0,
  2730. rendcirc ? (unsigned) TO_CIRCUIT(rendcirc)->n_circ_id : 0,
  2731. rendcirc ? rendcirc->global_identifier : 0, conn_age);
  2732. return 0;
  2733. }
  2734. }
  2735. /** Change <b>circ</b>'s purpose to <b>new_purpose</b>. */
  2736. void
  2737. circuit_change_purpose(circuit_t *circ, uint8_t new_purpose)
  2738. {
  2739. uint8_t old_purpose;
  2740. /* Don't allow an OR circ to become an origin circ or vice versa. */
  2741. tor_assert(!!(CIRCUIT_IS_ORIGIN(circ)) ==
  2742. !!(CIRCUIT_PURPOSE_IS_ORIGIN(new_purpose)));
  2743. if (circ->purpose == new_purpose) return;
  2744. if (CIRCUIT_IS_ORIGIN(circ)) {
  2745. char old_purpose_desc[80] = "";
  2746. strncpy(old_purpose_desc, circuit_purpose_to_string(circ->purpose), 80-1);
  2747. old_purpose_desc[80-1] = '\0';
  2748. log_debug(LD_CIRC,
  2749. "changing purpose of origin circ %d "
  2750. "from \"%s\" (%d) to \"%s\" (%d)",
  2751. TO_ORIGIN_CIRCUIT(circ)->global_identifier,
  2752. old_purpose_desc,
  2753. circ->purpose,
  2754. circuit_purpose_to_string(new_purpose),
  2755. new_purpose);
  2756. }
  2757. old_purpose = circ->purpose;
  2758. circ->purpose = new_purpose;
  2759. if (CIRCUIT_IS_ORIGIN(circ)) {
  2760. control_event_circuit_purpose_changed(TO_ORIGIN_CIRCUIT(circ),
  2761. old_purpose);
  2762. }
  2763. }
  2764. /** Mark <b>circ</b> so that no more connections can be attached to it. */
  2765. void
  2766. mark_circuit_unusable_for_new_conns(origin_circuit_t *circ)
  2767. {
  2768. const or_options_t *options = get_options();
  2769. tor_assert(circ);
  2770. /* XXXX This is a kludge; we're only keeping it around in case there's
  2771. * something that doesn't check unusable_for_new_conns, and to avoid
  2772. * deeper refactoring of our expiration logic. */
  2773. if (! circ->base_.timestamp_dirty)
  2774. circ->base_.timestamp_dirty = approx_time();
  2775. if (options->MaxCircuitDirtiness >= circ->base_.timestamp_dirty)
  2776. circ->base_.timestamp_dirty = 1; /* prevent underflow */
  2777. else
  2778. circ->base_.timestamp_dirty -= options->MaxCircuitDirtiness;
  2779. circ->unusable_for_new_conns = 1;
  2780. }
  2781. /**
  2782. * Add relay_body_len and RELAY_PAYLOAD_SIZE-relay_body_len to
  2783. * the valid delivered written fields and the overhead field,
  2784. * respectively.
  2785. */
  2786. void
  2787. circuit_sent_valid_data(origin_circuit_t *circ, uint16_t relay_body_len)
  2788. {
  2789. if (!circ) return;
  2790. tor_assert_nonfatal(relay_body_len <= RELAY_PAYLOAD_SIZE);
  2791. circ->n_delivered_written_circ_bw =
  2792. tor_add_u32_nowrap(circ->n_delivered_written_circ_bw, relay_body_len);
  2793. circ->n_overhead_written_circ_bw =
  2794. tor_add_u32_nowrap(circ->n_overhead_written_circ_bw,
  2795. RELAY_PAYLOAD_SIZE-relay_body_len);
  2796. }
  2797. /**
  2798. * Add relay_body_len and RELAY_PAYLOAD_SIZE-relay_body_len to
  2799. * the valid delivered read field and the overhead field,
  2800. * respectively.
  2801. */
  2802. void
  2803. circuit_read_valid_data(origin_circuit_t *circ, uint16_t relay_body_len)
  2804. {
  2805. if (!circ) return;
  2806. tor_assert_nonfatal(relay_body_len <= RELAY_PAYLOAD_SIZE);
  2807. circ->n_delivered_read_circ_bw =
  2808. tor_add_u32_nowrap(circ->n_delivered_read_circ_bw, relay_body_len);
  2809. circ->n_overhead_read_circ_bw =
  2810. tor_add_u32_nowrap(circ->n_overhead_read_circ_bw,
  2811. RELAY_PAYLOAD_SIZE-relay_body_len);
  2812. }