circuitlist.c 91 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826
  1. /* Copyright 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 circuitlist.c
  8. *
  9. * \brief Manage global structures that list and index circuits, and
  10. * look up circuits within them.
  11. *
  12. * One of the most frequent operations in Tor occurs every time that
  13. * a relay cell arrives on a channel. When that happens, we need to
  14. * find which circuit it is associated with, based on the channel and the
  15. * circuit ID in the relay cell.
  16. *
  17. * To handle that, we maintain a global list of circuits, and a hashtable
  18. * mapping [channel,circID] pairs to circuits. Circuits are added to and
  19. * removed from this mapping using circuit_set_p_circid_chan() and
  20. * circuit_set_n_circid_chan(). To look up a circuit from this map, most
  21. * callers should use circuit_get_by_circid_channel(), though
  22. * circuit_get_by_circid_channel_even_if_marked() is appropriate under some
  23. * circumstances.
  24. *
  25. * We also need to allow for the possibility that we have blocked use of a
  26. * circuit ID (because we are waiting to send a DESTROY cell), but the
  27. * circuit is not there any more. For that case, we allow placeholder
  28. * entries in the table, using channel_mark_circid_unusable().
  29. *
  30. * To efficiently handle a channel that has just opened, we also maintain a
  31. * list of the circuits waiting for channels, so we can attach them as
  32. * needed without iterating through the whole list of circuits, using
  33. * circuit_get_all_pending_on_channel().
  34. *
  35. * In this module, we also handle the list of circuits that have been
  36. * marked for close elsewhere, and close them as needed. (We use this
  37. * "mark now, close later" pattern here and elsewhere to avoid
  38. * unpredictable recursion if we closed every circuit immediately upon
  39. * realizing it needed to close.) See circuit_mark_for_close() for the
  40. * mark function, and circuit_close_all_marked() for the close function.
  41. *
  42. * For hidden services, we need to be able to look up introduction point
  43. * circuits and rendezvous circuits by cookie, key, etc. These are
  44. * currently handled with linear searches in
  45. * circuit_get_ready_rend_circuit_by_rend_data(),
  46. * circuit_get_next_by_pk_and_purpose(), and with hash lookups in
  47. * circuit_get_rendezvous() and circuit_get_intro_point().
  48. *
  49. * This module is also the entry point for our out-of-memory handler
  50. * logic, which was originally circuit-focused.
  51. **/
  52. #define CIRCUITLIST_PRIVATE
  53. #include "lib/cc/torint.h" /* TOR_PRIuSZ */
  54. #include "core/or/or.h"
  55. #include "core/or/channel.h"
  56. #include "core/or/channeltls.h"
  57. #include "feature/client/circpathbias.h"
  58. #include "core/or/circuitbuild.h"
  59. #include "core/or/circuitlist.h"
  60. #include "core/or/circuituse.h"
  61. #include "core/or/circuitstats.h"
  62. #include "core/mainloop/connection.h"
  63. #include "app/config/config.h"
  64. #include "core/or/connection_edge.h"
  65. #include "core/or/connection_or.h"
  66. #include "feature/control/control.h"
  67. #include "lib/crypt_ops/crypto_rand.h"
  68. #include "lib/crypt_ops/crypto_util.h"
  69. #include "lib/crypt_ops/crypto_dh.h"
  70. #include "feature/dircache/directory.h"
  71. #include "feature/client/entrynodes.h"
  72. #include "core/mainloop/main.h"
  73. #include "feature/hs/hs_circuit.h"
  74. #include "feature/hs/hs_circuitmap.h"
  75. #include "feature/hs/hs_ident.h"
  76. #include "feature/nodelist/networkstatus.h"
  77. #include "feature/nodelist/nodelist.h"
  78. #include "core/crypto/onion.h"
  79. #include "core/crypto/onion_fast.h"
  80. #include "core/or/policies.h"
  81. #include "core/or/relay.h"
  82. #include "core/crypto/relay_crypto.h"
  83. #include "feature/rend/rendclient.h"
  84. #include "feature/rend/rendcommon.h"
  85. #include "feature/stats/rephist.h"
  86. #include "feature/nodelist/routerlist.h"
  87. #include "feature/nodelist/routerset.h"
  88. #include "core/or/channelpadding.h"
  89. #include "lib/compress/compress.h"
  90. #include "lib/compress/compress_lzma.h"
  91. #include "lib/compress/compress_zlib.h"
  92. #include "lib/compress/compress_zstd.h"
  93. #include "lib/container/buffers.h"
  94. #include "ht.h"
  95. #include "core/or/cpath_build_state_st.h"
  96. #include "core/or/crypt_path_reference_st.h"
  97. #include "feature/dircommon/dir_connection_st.h"
  98. #include "core/or/edge_connection_st.h"
  99. #include "core/or/half_edge_st.h"
  100. #include "core/or/extend_info_st.h"
  101. #include "core/or/or_circuit_st.h"
  102. #include "core/or/origin_circuit_st.h"
  103. /********* START VARIABLES **********/
  104. /** A global list of all circuits at this hop. */
  105. static smartlist_t *global_circuitlist = NULL;
  106. /** A global list of all origin circuits. Every element of this is also
  107. * an element of global_circuitlist. */
  108. static smartlist_t *global_origin_circuit_list = NULL;
  109. /** A list of all the circuits in CIRCUIT_STATE_CHAN_WAIT. */
  110. static smartlist_t *circuits_pending_chans = NULL;
  111. /** List of all the (origin) circuits whose state is
  112. * CIRCUIT_STATE_GUARD_WAIT. */
  113. static smartlist_t *circuits_pending_other_guards = NULL;
  114. /** A list of all the circuits that have been marked with
  115. * circuit_mark_for_close and which are waiting for circuit_about_to_free. */
  116. static smartlist_t *circuits_pending_close = NULL;
  117. static void circuit_free_cpath_node(crypt_path_t *victim);
  118. static void cpath_ref_decref(crypt_path_reference_t *cpath_ref);
  119. static void circuit_about_to_free_atexit(circuit_t *circ);
  120. static void circuit_about_to_free(circuit_t *circ);
  121. /**
  122. * A cached value of the current state of the origin circuit list. Has the
  123. * value 1 if we saw any opened circuits recently (since the last call to
  124. * circuit_any_opened_circuits(), which gets called around once a second by
  125. * circuit_expire_building). 0 otherwise.
  126. */
  127. static int any_opened_circs_cached_val = 0;
  128. /********* END VARIABLES ************/
  129. or_circuit_t *
  130. TO_OR_CIRCUIT(circuit_t *x)
  131. {
  132. tor_assert(x->magic == OR_CIRCUIT_MAGIC);
  133. return DOWNCAST(or_circuit_t, x);
  134. }
  135. const or_circuit_t *
  136. CONST_TO_OR_CIRCUIT(const circuit_t *x)
  137. {
  138. tor_assert(x->magic == OR_CIRCUIT_MAGIC);
  139. return DOWNCAST(or_circuit_t, x);
  140. }
  141. origin_circuit_t *
  142. TO_ORIGIN_CIRCUIT(circuit_t *x)
  143. {
  144. tor_assert(x->magic == ORIGIN_CIRCUIT_MAGIC);
  145. return DOWNCAST(origin_circuit_t, x);
  146. }
  147. const origin_circuit_t *
  148. CONST_TO_ORIGIN_CIRCUIT(const circuit_t *x)
  149. {
  150. tor_assert(x->magic == ORIGIN_CIRCUIT_MAGIC);
  151. return DOWNCAST(origin_circuit_t, x);
  152. }
  153. /** A map from channel and circuit ID to circuit. (Lookup performance is
  154. * very important here, since we need to do it every time a cell arrives.) */
  155. typedef struct chan_circid_circuit_map_t {
  156. HT_ENTRY(chan_circid_circuit_map_t) node;
  157. channel_t *chan;
  158. circid_t circ_id;
  159. circuit_t *circuit;
  160. /* For debugging 12184: when was this placeholder item added? */
  161. time_t made_placeholder_at;
  162. } chan_circid_circuit_map_t;
  163. /** Helper for hash tables: compare the channel and circuit ID for a and
  164. * b, and return less than, equal to, or greater than zero appropriately.
  165. */
  166. static inline int
  167. chan_circid_entries_eq_(chan_circid_circuit_map_t *a,
  168. chan_circid_circuit_map_t *b)
  169. {
  170. return a->chan == b->chan && a->circ_id == b->circ_id;
  171. }
  172. /** Helper: return a hash based on circuit ID and the pointer value of
  173. * chan in <b>a</b>. */
  174. static inline unsigned int
  175. chan_circid_entry_hash_(chan_circid_circuit_map_t *a)
  176. {
  177. /* Try to squeze the siphash input into 8 bytes to save any extra siphash
  178. * rounds. This hash function is in the critical path. */
  179. uintptr_t chan = (uintptr_t) (void*) a->chan;
  180. uint32_t array[2];
  181. array[0] = a->circ_id;
  182. /* The low bits of the channel pointer are uninteresting, since the channel
  183. * is a pretty big structure. */
  184. array[1] = (uint32_t) (chan >> 6);
  185. return (unsigned) siphash24g(array, sizeof(array));
  186. }
  187. /** Map from [chan,circid] to circuit. */
  188. static HT_HEAD(chan_circid_map, chan_circid_circuit_map_t)
  189. chan_circid_map = HT_INITIALIZER();
  190. HT_PROTOTYPE(chan_circid_map, chan_circid_circuit_map_t, node,
  191. chan_circid_entry_hash_, chan_circid_entries_eq_)
  192. HT_GENERATE2(chan_circid_map, chan_circid_circuit_map_t, node,
  193. chan_circid_entry_hash_, chan_circid_entries_eq_, 0.6,
  194. tor_reallocarray_, tor_free_)
  195. /** The most recently returned entry from circuit_get_by_circid_chan;
  196. * used to improve performance when many cells arrive in a row from the
  197. * same circuit.
  198. */
  199. static chan_circid_circuit_map_t *_last_circid_chan_ent = NULL;
  200. /** Implementation helper for circuit_set_{p,n}_circid_channel: A circuit ID
  201. * and/or channel for circ has just changed from <b>old_chan, old_id</b>
  202. * to <b>chan, id</b>. Adjust the chan,circid map as appropriate, removing
  203. * the old entry (if any) and adding a new one. */
  204. static void
  205. circuit_set_circid_chan_helper(circuit_t *circ, int direction,
  206. circid_t id,
  207. channel_t *chan)
  208. {
  209. chan_circid_circuit_map_t search;
  210. chan_circid_circuit_map_t *found;
  211. channel_t *old_chan, **chan_ptr;
  212. circid_t old_id, *circid_ptr;
  213. int make_active, attached = 0;
  214. if (direction == CELL_DIRECTION_OUT) {
  215. chan_ptr = &circ->n_chan;
  216. circid_ptr = &circ->n_circ_id;
  217. make_active = circ->n_chan_cells.n > 0;
  218. } else {
  219. or_circuit_t *c = TO_OR_CIRCUIT(circ);
  220. chan_ptr = &c->p_chan;
  221. circid_ptr = &c->p_circ_id;
  222. make_active = c->p_chan_cells.n > 0;
  223. }
  224. old_chan = *chan_ptr;
  225. old_id = *circid_ptr;
  226. if (id == old_id && chan == old_chan)
  227. return;
  228. if (_last_circid_chan_ent &&
  229. ((old_id == _last_circid_chan_ent->circ_id &&
  230. old_chan == _last_circid_chan_ent->chan) ||
  231. (id == _last_circid_chan_ent->circ_id &&
  232. chan == _last_circid_chan_ent->chan))) {
  233. _last_circid_chan_ent = NULL;
  234. }
  235. if (old_chan) {
  236. /*
  237. * If we're changing channels or ID and had an old channel and a non
  238. * zero old ID and weren't marked for close (i.e., we should have been
  239. * attached), detach the circuit. ID changes require this because
  240. * circuitmux hashes on (channel_id, circuit_id).
  241. */
  242. if (old_id != 0 && (old_chan != chan || old_id != id) &&
  243. !(circ->marked_for_close)) {
  244. tor_assert(old_chan->cmux);
  245. circuitmux_detach_circuit(old_chan->cmux, circ);
  246. }
  247. /* we may need to remove it from the conn-circid map */
  248. search.circ_id = old_id;
  249. search.chan = old_chan;
  250. found = HT_REMOVE(chan_circid_map, &chan_circid_map, &search);
  251. if (found) {
  252. tor_free(found);
  253. if (direction == CELL_DIRECTION_OUT) {
  254. /* One fewer circuits use old_chan as n_chan */
  255. --(old_chan->num_n_circuits);
  256. } else {
  257. /* One fewer circuits use old_chan as p_chan */
  258. --(old_chan->num_p_circuits);
  259. }
  260. }
  261. }
  262. /* Change the values only after we have possibly made the circuit inactive
  263. * on the previous chan. */
  264. *chan_ptr = chan;
  265. *circid_ptr = id;
  266. if (chan == NULL)
  267. return;
  268. /* now add the new one to the conn-circid map */
  269. search.circ_id = id;
  270. search.chan = chan;
  271. found = HT_FIND(chan_circid_map, &chan_circid_map, &search);
  272. if (found) {
  273. found->circuit = circ;
  274. found->made_placeholder_at = 0;
  275. } else {
  276. found = tor_malloc_zero(sizeof(chan_circid_circuit_map_t));
  277. found->circ_id = id;
  278. found->chan = chan;
  279. found->circuit = circ;
  280. HT_INSERT(chan_circid_map, &chan_circid_map, found);
  281. }
  282. /*
  283. * Attach to the circuitmux if we're changing channels or IDs and
  284. * have a new channel and ID to use and the circuit is not marked for
  285. * close.
  286. */
  287. if (chan && id != 0 && (old_chan != chan || old_id != id) &&
  288. !(circ->marked_for_close)) {
  289. tor_assert(chan->cmux);
  290. circuitmux_attach_circuit(chan->cmux, circ, direction);
  291. attached = 1;
  292. }
  293. /*
  294. * This is a no-op if we have no cells, but if we do it marks us active to
  295. * the circuitmux
  296. */
  297. if (make_active && attached)
  298. update_circuit_on_cmux(circ, direction);
  299. /* Adjust circuit counts on new channel */
  300. if (direction == CELL_DIRECTION_OUT) {
  301. ++chan->num_n_circuits;
  302. } else {
  303. ++chan->num_p_circuits;
  304. }
  305. }
  306. /** Mark that circuit id <b>id</b> shouldn't be used on channel <b>chan</b>,
  307. * even if there is no circuit on the channel. We use this to keep the
  308. * circuit id from getting re-used while we have queued but not yet sent
  309. * a destroy cell. */
  310. void
  311. channel_mark_circid_unusable(channel_t *chan, circid_t id)
  312. {
  313. chan_circid_circuit_map_t search;
  314. chan_circid_circuit_map_t *ent;
  315. /* See if there's an entry there. That wouldn't be good. */
  316. memset(&search, 0, sizeof(search));
  317. search.chan = chan;
  318. search.circ_id = id;
  319. ent = HT_FIND(chan_circid_map, &chan_circid_map, &search);
  320. if (ent && ent->circuit) {
  321. /* we have a problem. */
  322. log_warn(LD_BUG, "Tried to mark %u unusable on %p, but there was already "
  323. "a circuit there.", (unsigned)id, chan);
  324. } else if (ent) {
  325. /* It's already marked. */
  326. if (!ent->made_placeholder_at)
  327. ent->made_placeholder_at = approx_time();
  328. } else {
  329. ent = tor_malloc_zero(sizeof(chan_circid_circuit_map_t));
  330. ent->chan = chan;
  331. ent->circ_id = id;
  332. /* leave circuit at NULL. */
  333. ent->made_placeholder_at = approx_time();
  334. HT_INSERT(chan_circid_map, &chan_circid_map, ent);
  335. }
  336. }
  337. /** Mark that a circuit id <b>id</b> can be used again on <b>chan</b>.
  338. * We use this to re-enable the circuit ID after we've sent a destroy cell.
  339. */
  340. void
  341. channel_mark_circid_usable(channel_t *chan, circid_t id)
  342. {
  343. chan_circid_circuit_map_t search;
  344. chan_circid_circuit_map_t *ent;
  345. /* See if there's an entry there. That wouldn't be good. */
  346. memset(&search, 0, sizeof(search));
  347. search.chan = chan;
  348. search.circ_id = id;
  349. ent = HT_REMOVE(chan_circid_map, &chan_circid_map, &search);
  350. if (ent && ent->circuit) {
  351. log_warn(LD_BUG, "Tried to mark %u usable on %p, but there was already "
  352. "a circuit there.", (unsigned)id, chan);
  353. return;
  354. }
  355. if (_last_circid_chan_ent == ent)
  356. _last_circid_chan_ent = NULL;
  357. tor_free(ent);
  358. }
  359. /** Called to indicate that a DESTROY is pending on <b>chan</b> with
  360. * circuit ID <b>id</b>, but hasn't been sent yet. */
  361. void
  362. channel_note_destroy_pending(channel_t *chan, circid_t id)
  363. {
  364. circuit_t *circ = circuit_get_by_circid_channel_even_if_marked(id,chan);
  365. if (circ) {
  366. if (circ->n_chan == chan && circ->n_circ_id == id) {
  367. circ->n_delete_pending = 1;
  368. } else {
  369. or_circuit_t *orcirc = TO_OR_CIRCUIT(circ);
  370. if (orcirc->p_chan == chan && orcirc->p_circ_id == id) {
  371. circ->p_delete_pending = 1;
  372. }
  373. }
  374. return;
  375. }
  376. channel_mark_circid_unusable(chan, id);
  377. }
  378. /** Called to indicate that a DESTROY is no longer pending on <b>chan</b> with
  379. * circuit ID <b>id</b> -- typically, because it has been sent. */
  380. MOCK_IMPL(void,
  381. channel_note_destroy_not_pending,(channel_t *chan, circid_t id))
  382. {
  383. circuit_t *circ = circuit_get_by_circid_channel_even_if_marked(id,chan);
  384. if (circ) {
  385. if (circ->n_chan == chan && circ->n_circ_id == id) {
  386. circ->n_delete_pending = 0;
  387. } else {
  388. or_circuit_t *orcirc = TO_OR_CIRCUIT(circ);
  389. if (orcirc->p_chan == chan && orcirc->p_circ_id == id) {
  390. circ->p_delete_pending = 0;
  391. }
  392. }
  393. /* XXXX this shouldn't happen; log a bug here. */
  394. return;
  395. }
  396. channel_mark_circid_usable(chan, id);
  397. }
  398. /** Set the p_conn field of a circuit <b>circ</b>, along
  399. * with the corresponding circuit ID, and add the circuit as appropriate
  400. * to the (chan,id)-\>circuit map. */
  401. void
  402. circuit_set_p_circid_chan(or_circuit_t *or_circ, circid_t id,
  403. channel_t *chan)
  404. {
  405. circuit_t *circ = TO_CIRCUIT(or_circ);
  406. channel_t *old_chan = or_circ->p_chan;
  407. circid_t old_id = or_circ->p_circ_id;
  408. circuit_set_circid_chan_helper(circ, CELL_DIRECTION_IN, id, chan);
  409. if (chan) {
  410. chan->timestamp_last_had_circuits = approx_time();
  411. }
  412. if (circ->p_delete_pending && old_chan) {
  413. channel_mark_circid_unusable(old_chan, old_id);
  414. circ->p_delete_pending = 0;
  415. }
  416. }
  417. /** Set the n_conn field of a circuit <b>circ</b>, along
  418. * with the corresponding circuit ID, and add the circuit as appropriate
  419. * to the (chan,id)-\>circuit map. */
  420. void
  421. circuit_set_n_circid_chan(circuit_t *circ, circid_t id,
  422. channel_t *chan)
  423. {
  424. channel_t *old_chan = circ->n_chan;
  425. circid_t old_id = circ->n_circ_id;
  426. circuit_set_circid_chan_helper(circ, CELL_DIRECTION_OUT, id, chan);
  427. if (chan) {
  428. chan->timestamp_last_had_circuits = approx_time();
  429. }
  430. if (circ->n_delete_pending && old_chan) {
  431. channel_mark_circid_unusable(old_chan, old_id);
  432. circ->n_delete_pending = 0;
  433. }
  434. }
  435. /** Change the state of <b>circ</b> to <b>state</b>, adding it to or removing
  436. * it from lists as appropriate. */
  437. void
  438. circuit_set_state(circuit_t *circ, uint8_t state)
  439. {
  440. tor_assert(circ);
  441. if (state == circ->state)
  442. return;
  443. if (PREDICT_UNLIKELY(!circuits_pending_chans))
  444. circuits_pending_chans = smartlist_new();
  445. if (PREDICT_UNLIKELY(!circuits_pending_other_guards))
  446. circuits_pending_other_guards = smartlist_new();
  447. if (circ->state == CIRCUIT_STATE_CHAN_WAIT) {
  448. /* remove from waiting-circuit list. */
  449. smartlist_remove(circuits_pending_chans, circ);
  450. }
  451. if (state == CIRCUIT_STATE_CHAN_WAIT) {
  452. /* add to waiting-circuit list. */
  453. smartlist_add(circuits_pending_chans, circ);
  454. }
  455. if (circ->state == CIRCUIT_STATE_GUARD_WAIT) {
  456. smartlist_remove(circuits_pending_other_guards, circ);
  457. }
  458. if (state == CIRCUIT_STATE_GUARD_WAIT) {
  459. smartlist_add(circuits_pending_other_guards, circ);
  460. }
  461. if (state == CIRCUIT_STATE_GUARD_WAIT || state == CIRCUIT_STATE_OPEN)
  462. tor_assert(!circ->n_chan_create_cell);
  463. circ->state = state;
  464. }
  465. /** Append to <b>out</b> all circuits in state CHAN_WAIT waiting for
  466. * the given connection. */
  467. void
  468. circuit_get_all_pending_on_channel(smartlist_t *out, channel_t *chan)
  469. {
  470. tor_assert(out);
  471. tor_assert(chan);
  472. if (!circuits_pending_chans)
  473. return;
  474. SMARTLIST_FOREACH_BEGIN(circuits_pending_chans, circuit_t *, circ) {
  475. if (circ->marked_for_close)
  476. continue;
  477. if (!circ->n_hop)
  478. continue;
  479. tor_assert(circ->state == CIRCUIT_STATE_CHAN_WAIT);
  480. if (tor_digest_is_zero(circ->n_hop->identity_digest)) {
  481. /* Look at addr/port. This is an unkeyed connection. */
  482. if (!channel_matches_extend_info(chan, circ->n_hop))
  483. continue;
  484. } else {
  485. /* We expected a key. See if it's the right one. */
  486. if (tor_memneq(chan->identity_digest,
  487. circ->n_hop->identity_digest, DIGEST_LEN))
  488. continue;
  489. }
  490. smartlist_add(out, circ);
  491. } SMARTLIST_FOREACH_END(circ);
  492. }
  493. /** Return the number of circuits in state CHAN_WAIT, waiting for the given
  494. * channel. */
  495. int
  496. circuit_count_pending_on_channel(channel_t *chan)
  497. {
  498. int cnt;
  499. smartlist_t *sl = smartlist_new();
  500. tor_assert(chan);
  501. circuit_get_all_pending_on_channel(sl, chan);
  502. cnt = smartlist_len(sl);
  503. smartlist_free(sl);
  504. log_debug(LD_CIRC,"or_conn to %s, %d pending circs",
  505. channel_get_canonical_remote_descr(chan),
  506. cnt);
  507. return cnt;
  508. }
  509. /** Remove <b>origin_circ</b> from the global list of origin circuits.
  510. * Called when we are freeing a circuit.
  511. */
  512. static void
  513. circuit_remove_from_origin_circuit_list(origin_circuit_t *origin_circ)
  514. {
  515. int origin_idx = origin_circ->global_origin_circuit_list_idx;
  516. if (origin_idx < 0)
  517. return;
  518. origin_circuit_t *c2;
  519. tor_assert(origin_idx <= smartlist_len(global_origin_circuit_list));
  520. c2 = smartlist_get(global_origin_circuit_list, origin_idx);
  521. tor_assert(origin_circ == c2);
  522. smartlist_del(global_origin_circuit_list, origin_idx);
  523. if (origin_idx < smartlist_len(global_origin_circuit_list)) {
  524. origin_circuit_t *replacement =
  525. smartlist_get(global_origin_circuit_list, origin_idx);
  526. replacement->global_origin_circuit_list_idx = origin_idx;
  527. }
  528. origin_circ->global_origin_circuit_list_idx = -1;
  529. }
  530. /** Add <b>origin_circ</b> to the global list of origin circuits. Called
  531. * when creating the circuit. */
  532. static void
  533. circuit_add_to_origin_circuit_list(origin_circuit_t *origin_circ)
  534. {
  535. tor_assert(origin_circ->global_origin_circuit_list_idx == -1);
  536. smartlist_t *lst = circuit_get_global_origin_circuit_list();
  537. smartlist_add(lst, origin_circ);
  538. origin_circ->global_origin_circuit_list_idx = smartlist_len(lst) - 1;
  539. }
  540. /** Detach from the global circuit list, and deallocate, all
  541. * circuits that have been marked for close.
  542. */
  543. void
  544. circuit_close_all_marked(void)
  545. {
  546. if (circuits_pending_close == NULL)
  547. return;
  548. smartlist_t *lst = circuit_get_global_list();
  549. SMARTLIST_FOREACH_BEGIN(circuits_pending_close, circuit_t *, circ) {
  550. tor_assert(circ->marked_for_close);
  551. /* Remove it from the circuit list. */
  552. int idx = circ->global_circuitlist_idx;
  553. smartlist_del(lst, idx);
  554. if (idx < smartlist_len(lst)) {
  555. circuit_t *replacement = smartlist_get(lst, idx);
  556. replacement->global_circuitlist_idx = idx;
  557. }
  558. circ->global_circuitlist_idx = -1;
  559. /* Remove it from the origin circuit list, if appropriate. */
  560. if (CIRCUIT_IS_ORIGIN(circ)) {
  561. circuit_remove_from_origin_circuit_list(TO_ORIGIN_CIRCUIT(circ));
  562. }
  563. circuit_about_to_free(circ);
  564. circuit_free(circ);
  565. } SMARTLIST_FOREACH_END(circ);
  566. smartlist_clear(circuits_pending_close);
  567. }
  568. /** Return a pointer to the global list of circuits. */
  569. MOCK_IMPL(smartlist_t *,
  570. circuit_get_global_list,(void))
  571. {
  572. if (NULL == global_circuitlist)
  573. global_circuitlist = smartlist_new();
  574. return global_circuitlist;
  575. }
  576. /** Return a pointer to the global list of origin circuits. */
  577. smartlist_t *
  578. circuit_get_global_origin_circuit_list(void)
  579. {
  580. if (NULL == global_origin_circuit_list)
  581. global_origin_circuit_list = smartlist_new();
  582. return global_origin_circuit_list;
  583. }
  584. /**
  585. * Return true if we have any opened general-purpose 3 hop
  586. * origin circuits.
  587. *
  588. * The result from this function is cached for use by
  589. * circuit_any_opened_circuits_cached().
  590. */
  591. int
  592. circuit_any_opened_circuits(void)
  593. {
  594. SMARTLIST_FOREACH_BEGIN(circuit_get_global_origin_circuit_list(),
  595. const origin_circuit_t *, next_circ) {
  596. if (!TO_CIRCUIT(next_circ)->marked_for_close &&
  597. next_circ->has_opened &&
  598. TO_CIRCUIT(next_circ)->state == CIRCUIT_STATE_OPEN &&
  599. TO_CIRCUIT(next_circ)->purpose != CIRCUIT_PURPOSE_C_MEASURE_TIMEOUT &&
  600. next_circ->build_state &&
  601. next_circ->build_state->desired_path_len == DEFAULT_ROUTE_LEN) {
  602. circuit_cache_opened_circuit_state(1);
  603. return 1;
  604. }
  605. } SMARTLIST_FOREACH_END(next_circ);
  606. circuit_cache_opened_circuit_state(0);
  607. return 0;
  608. }
  609. /**
  610. * Cache the "any circuits opened" state, as specified in param
  611. * circuits_are_opened. This is a helper function to update
  612. * the circuit opened status whenever we happen to look at the
  613. * circuit list.
  614. */
  615. void
  616. circuit_cache_opened_circuit_state(int circuits_are_opened)
  617. {
  618. any_opened_circs_cached_val = circuits_are_opened;
  619. }
  620. /**
  621. * Return true if there were any opened circuits since the last call to
  622. * circuit_any_opened_circuits(), or since circuit_expire_building() last
  623. * ran (it runs roughly once per second).
  624. */
  625. int
  626. circuit_any_opened_circuits_cached(void)
  627. {
  628. return any_opened_circs_cached_val;
  629. }
  630. /** Function to make circ-\>state human-readable */
  631. const char *
  632. circuit_state_to_string(int state)
  633. {
  634. static char buf[64];
  635. switch (state) {
  636. case CIRCUIT_STATE_BUILDING: return "doing handshakes";
  637. case CIRCUIT_STATE_ONIONSKIN_PENDING: return "processing the onion";
  638. case CIRCUIT_STATE_CHAN_WAIT: return "connecting to server";
  639. case CIRCUIT_STATE_GUARD_WAIT: return "waiting to see how other "
  640. "guards perform";
  641. case CIRCUIT_STATE_OPEN: return "open";
  642. default:
  643. log_warn(LD_BUG, "Unknown circuit state %d", state);
  644. tor_snprintf(buf, sizeof(buf), "unknown state [%d]", state);
  645. return buf;
  646. }
  647. }
  648. /** Map a circuit purpose to a string suitable to be displayed to a
  649. * controller. */
  650. const char *
  651. circuit_purpose_to_controller_string(uint8_t purpose)
  652. {
  653. static char buf[32];
  654. switch (purpose) {
  655. case CIRCUIT_PURPOSE_OR:
  656. case CIRCUIT_PURPOSE_INTRO_POINT:
  657. case CIRCUIT_PURPOSE_REND_POINT_WAITING:
  658. case CIRCUIT_PURPOSE_REND_ESTABLISHED:
  659. return "SERVER"; /* A controller should never see these, actually. */
  660. case CIRCUIT_PURPOSE_C_GENERAL:
  661. return "GENERAL";
  662. case CIRCUIT_PURPOSE_C_HSDIR_GET:
  663. return "HS_CLIENT_HSDIR";
  664. case CIRCUIT_PURPOSE_C_INTRODUCING:
  665. case CIRCUIT_PURPOSE_C_INTRODUCE_ACK_WAIT:
  666. case CIRCUIT_PURPOSE_C_INTRODUCE_ACKED:
  667. return "HS_CLIENT_INTRO";
  668. case CIRCUIT_PURPOSE_C_ESTABLISH_REND:
  669. case CIRCUIT_PURPOSE_C_REND_READY:
  670. case CIRCUIT_PURPOSE_C_REND_READY_INTRO_ACKED:
  671. case CIRCUIT_PURPOSE_C_REND_JOINED:
  672. return "HS_CLIENT_REND";
  673. case CIRCUIT_PURPOSE_S_HSDIR_POST:
  674. return "HS_SERVICE_HSDIR";
  675. case CIRCUIT_PURPOSE_S_ESTABLISH_INTRO:
  676. case CIRCUIT_PURPOSE_S_INTRO:
  677. return "HS_SERVICE_INTRO";
  678. case CIRCUIT_PURPOSE_S_CONNECT_REND:
  679. case CIRCUIT_PURPOSE_S_REND_JOINED:
  680. return "HS_SERVICE_REND";
  681. case CIRCUIT_PURPOSE_TESTING:
  682. return "TESTING";
  683. case CIRCUIT_PURPOSE_C_MEASURE_TIMEOUT:
  684. return "MEASURE_TIMEOUT";
  685. case CIRCUIT_PURPOSE_CONTROLLER:
  686. return "CONTROLLER";
  687. case CIRCUIT_PURPOSE_PATH_BIAS_TESTING:
  688. return "PATH_BIAS_TESTING";
  689. case CIRCUIT_PURPOSE_HS_VANGUARDS:
  690. return "HS_VANGUARDS";
  691. default:
  692. tor_snprintf(buf, sizeof(buf), "UNKNOWN_%d", (int)purpose);
  693. return buf;
  694. }
  695. }
  696. /** Return a string specifying the state of the hidden-service circuit
  697. * purpose <b>purpose</b>, or NULL if <b>purpose</b> is not a
  698. * hidden-service-related circuit purpose. */
  699. const char *
  700. circuit_purpose_to_controller_hs_state_string(uint8_t purpose)
  701. {
  702. switch (purpose)
  703. {
  704. default:
  705. log_fn(LOG_WARN, LD_BUG,
  706. "Unrecognized circuit purpose: %d",
  707. (int)purpose);
  708. tor_fragile_assert();
  709. /* fall through */
  710. case CIRCUIT_PURPOSE_OR:
  711. case CIRCUIT_PURPOSE_C_GENERAL:
  712. case CIRCUIT_PURPOSE_C_MEASURE_TIMEOUT:
  713. case CIRCUIT_PURPOSE_TESTING:
  714. case CIRCUIT_PURPOSE_CONTROLLER:
  715. case CIRCUIT_PURPOSE_PATH_BIAS_TESTING:
  716. case CIRCUIT_PURPOSE_HS_VANGUARDS:
  717. return NULL;
  718. case CIRCUIT_PURPOSE_INTRO_POINT:
  719. return "OR_HSSI_ESTABLISHED";
  720. case CIRCUIT_PURPOSE_REND_POINT_WAITING:
  721. return "OR_HSCR_ESTABLISHED";
  722. case CIRCUIT_PURPOSE_REND_ESTABLISHED:
  723. return "OR_HS_R_JOINED";
  724. case CIRCUIT_PURPOSE_C_HSDIR_GET:
  725. case CIRCUIT_PURPOSE_C_INTRODUCING:
  726. return "HSCI_CONNECTING";
  727. case CIRCUIT_PURPOSE_C_INTRODUCE_ACK_WAIT:
  728. return "HSCI_INTRO_SENT";
  729. case CIRCUIT_PURPOSE_C_INTRODUCE_ACKED:
  730. return "HSCI_DONE";
  731. case CIRCUIT_PURPOSE_C_ESTABLISH_REND:
  732. return "HSCR_CONNECTING";
  733. case CIRCUIT_PURPOSE_C_REND_READY:
  734. return "HSCR_ESTABLISHED_IDLE";
  735. case CIRCUIT_PURPOSE_C_REND_READY_INTRO_ACKED:
  736. return "HSCR_ESTABLISHED_WAITING";
  737. case CIRCUIT_PURPOSE_C_REND_JOINED:
  738. return "HSCR_JOINED";
  739. case CIRCUIT_PURPOSE_S_HSDIR_POST:
  740. case CIRCUIT_PURPOSE_S_ESTABLISH_INTRO:
  741. return "HSSI_CONNECTING";
  742. case CIRCUIT_PURPOSE_S_INTRO:
  743. return "HSSI_ESTABLISHED";
  744. case CIRCUIT_PURPOSE_S_CONNECT_REND:
  745. return "HSSR_CONNECTING";
  746. case CIRCUIT_PURPOSE_S_REND_JOINED:
  747. return "HSSR_JOINED";
  748. }
  749. }
  750. /** Return a human-readable string for the circuit purpose <b>purpose</b>. */
  751. const char *
  752. circuit_purpose_to_string(uint8_t purpose)
  753. {
  754. static char buf[32];
  755. switch (purpose)
  756. {
  757. case CIRCUIT_PURPOSE_OR:
  758. return "Circuit at relay";
  759. case CIRCUIT_PURPOSE_INTRO_POINT:
  760. return "Acting as intro point";
  761. case CIRCUIT_PURPOSE_REND_POINT_WAITING:
  762. return "Acting as rendezvous (pending)";
  763. case CIRCUIT_PURPOSE_REND_ESTABLISHED:
  764. return "Acting as rendezvous (established)";
  765. case CIRCUIT_PURPOSE_C_GENERAL:
  766. return "General-purpose client";
  767. case CIRCUIT_PURPOSE_C_INTRODUCING:
  768. return "Hidden service client: Connecting to intro point";
  769. case CIRCUIT_PURPOSE_C_INTRODUCE_ACK_WAIT:
  770. return "Hidden service client: Waiting for ack from intro point";
  771. case CIRCUIT_PURPOSE_C_INTRODUCE_ACKED:
  772. return "Hidden service client: Received ack from intro point";
  773. case CIRCUIT_PURPOSE_C_ESTABLISH_REND:
  774. return "Hidden service client: Establishing rendezvous point";
  775. case CIRCUIT_PURPOSE_C_REND_READY:
  776. return "Hidden service client: Pending rendezvous point";
  777. case CIRCUIT_PURPOSE_C_REND_READY_INTRO_ACKED:
  778. return "Hidden service client: Pending rendezvous point (ack received)";
  779. case CIRCUIT_PURPOSE_C_REND_JOINED:
  780. return "Hidden service client: Active rendezvous point";
  781. case CIRCUIT_PURPOSE_C_HSDIR_GET:
  782. return "Hidden service client: Fetching HS descriptor";
  783. case CIRCUIT_PURPOSE_C_MEASURE_TIMEOUT:
  784. return "Measuring circuit timeout";
  785. case CIRCUIT_PURPOSE_S_ESTABLISH_INTRO:
  786. return "Hidden service: Establishing introduction point";
  787. case CIRCUIT_PURPOSE_S_INTRO:
  788. return "Hidden service: Introduction point";
  789. case CIRCUIT_PURPOSE_S_CONNECT_REND:
  790. return "Hidden service: Connecting to rendezvous point";
  791. case CIRCUIT_PURPOSE_S_REND_JOINED:
  792. return "Hidden service: Active rendezvous point";
  793. case CIRCUIT_PURPOSE_S_HSDIR_POST:
  794. return "Hidden service: Uploading HS descriptor";
  795. case CIRCUIT_PURPOSE_TESTING:
  796. return "Testing circuit";
  797. case CIRCUIT_PURPOSE_CONTROLLER:
  798. return "Circuit made by controller";
  799. case CIRCUIT_PURPOSE_PATH_BIAS_TESTING:
  800. return "Path-bias testing circuit";
  801. case CIRCUIT_PURPOSE_HS_VANGUARDS:
  802. return "Hidden service: Pre-built vanguard circuit";
  803. default:
  804. tor_snprintf(buf, sizeof(buf), "UNKNOWN_%d", (int)purpose);
  805. return buf;
  806. }
  807. }
  808. /** Pick a reasonable package_window to start out for our circuits.
  809. * Originally this was hard-coded at 1000, but now the consensus votes
  810. * on the answer. See proposal 168. */
  811. int32_t
  812. circuit_initial_package_window(void)
  813. {
  814. int32_t num = networkstatus_get_param(NULL, "circwindow", CIRCWINDOW_START,
  815. CIRCWINDOW_START_MIN,
  816. CIRCWINDOW_START_MAX);
  817. /* If the consensus tells us a negative number, we'd assert. */
  818. if (num < 0)
  819. num = CIRCWINDOW_START;
  820. return num;
  821. }
  822. /** Initialize the common elements in a circuit_t, and add it to the global
  823. * list. */
  824. static void
  825. init_circuit_base(circuit_t *circ)
  826. {
  827. tor_gettimeofday(&circ->timestamp_created);
  828. // Gets reset when we send CREATE_FAST.
  829. // circuit_expire_building() expects these to be equal
  830. // until the orconn is built.
  831. circ->timestamp_began = circ->timestamp_created;
  832. circ->package_window = circuit_initial_package_window();
  833. circ->deliver_window = CIRCWINDOW_START;
  834. cell_queue_init(&circ->n_chan_cells);
  835. smartlist_add(circuit_get_global_list(), circ);
  836. circ->global_circuitlist_idx = smartlist_len(circuit_get_global_list()) - 1;
  837. }
  838. /** If we haven't yet decided on a good timeout value for circuit
  839. * building, we close idle circuits aggressively so we can get more
  840. * data points. These are the default, min, and max consensus values */
  841. #define DFLT_IDLE_TIMEOUT_WHILE_LEARNING (3*60)
  842. #define MIN_IDLE_TIMEOUT_WHILE_LEARNING (10)
  843. #define MAX_IDLE_TIMEOUT_WHILE_LEARNING (1000*60)
  844. /** Allocate space for a new circuit, initializing with <b>p_circ_id</b>
  845. * and <b>p_conn</b>. Add it to the global circuit list.
  846. */
  847. origin_circuit_t *
  848. origin_circuit_new(void)
  849. {
  850. origin_circuit_t *circ;
  851. /* never zero, since a global ID of 0 is treated specially by the
  852. * controller */
  853. static uint32_t n_circuits_allocated = 1;
  854. circ = tor_malloc_zero(sizeof(origin_circuit_t));
  855. circ->base_.magic = ORIGIN_CIRCUIT_MAGIC;
  856. circ->next_stream_id = crypto_rand_int(1<<16);
  857. circ->global_identifier = n_circuits_allocated++;
  858. circ->remaining_relay_early_cells = MAX_RELAY_EARLY_CELLS_PER_CIRCUIT;
  859. circ->remaining_relay_early_cells -= crypto_rand_int(2);
  860. init_circuit_base(TO_CIRCUIT(circ));
  861. /* Add to origin-list. */
  862. circ->global_origin_circuit_list_idx = -1;
  863. circuit_add_to_origin_circuit_list(circ);
  864. circuit_build_times_update_last_circ(get_circuit_build_times_mutable());
  865. if (! circuit_build_times_disabled(get_options()) &&
  866. circuit_build_times_needs_circuits(get_circuit_build_times())) {
  867. /* Circuits should be shorter lived if we need more of them
  868. * for learning a good build timeout */
  869. circ->circuit_idle_timeout =
  870. networkstatus_get_param(NULL, "cbtlearntimeout",
  871. DFLT_IDLE_TIMEOUT_WHILE_LEARNING,
  872. MIN_IDLE_TIMEOUT_WHILE_LEARNING,
  873. MAX_IDLE_TIMEOUT_WHILE_LEARNING);
  874. } else {
  875. // This should always be larger than the current port prediction time
  876. // remaining, or else we'll end up with the case where a circuit times out
  877. // and another one is built, effectively doubling the timeout window.
  878. //
  879. // We also randomize it by up to 5% more (ie 5% of 0 to 3600 seconds,
  880. // depending on how much circuit prediction time is remaining) so that
  881. // we don't close a bunch of unused circuits all at the same time.
  882. int prediction_time_remaining =
  883. predicted_ports_prediction_time_remaining(time(NULL));
  884. circ->circuit_idle_timeout = prediction_time_remaining+1+
  885. crypto_rand_int(1+prediction_time_remaining/20);
  886. if (circ->circuit_idle_timeout <= 0) {
  887. log_warn(LD_BUG,
  888. "Circuit chose a negative idle timeout of %d based on "
  889. "%d seconds of predictive building remaining.",
  890. circ->circuit_idle_timeout,
  891. prediction_time_remaining);
  892. circ->circuit_idle_timeout =
  893. networkstatus_get_param(NULL, "cbtlearntimeout",
  894. DFLT_IDLE_TIMEOUT_WHILE_LEARNING,
  895. MIN_IDLE_TIMEOUT_WHILE_LEARNING,
  896. MAX_IDLE_TIMEOUT_WHILE_LEARNING);
  897. }
  898. log_info(LD_CIRC,
  899. "Circuit %"PRIu32" chose an idle timeout of %d based on "
  900. "%d seconds of predictive building remaining.",
  901. (circ->global_identifier),
  902. circ->circuit_idle_timeout,
  903. prediction_time_remaining);
  904. }
  905. return circ;
  906. }
  907. /** Allocate a new or_circuit_t, connected to <b>p_chan</b> as
  908. * <b>p_circ_id</b>. If <b>p_chan</b> is NULL, the circuit is unattached. */
  909. or_circuit_t *
  910. or_circuit_new(circid_t p_circ_id, channel_t *p_chan)
  911. {
  912. /* CircIDs */
  913. or_circuit_t *circ;
  914. circ = tor_malloc_zero(sizeof(or_circuit_t));
  915. circ->base_.magic = OR_CIRCUIT_MAGIC;
  916. if (p_chan)
  917. circuit_set_p_circid_chan(circ, p_circ_id, p_chan);
  918. circ->remaining_relay_early_cells = MAX_RELAY_EARLY_CELLS_PER_CIRCUIT;
  919. cell_queue_init(&circ->p_chan_cells);
  920. init_circuit_base(TO_CIRCUIT(circ));
  921. return circ;
  922. }
  923. /** Free all storage held in circ->testing_cell_stats */
  924. void
  925. circuit_clear_testing_cell_stats(circuit_t *circ)
  926. {
  927. if (!circ || !circ->testing_cell_stats)
  928. return;
  929. SMARTLIST_FOREACH(circ->testing_cell_stats, testing_cell_stats_entry_t *,
  930. ent, tor_free(ent));
  931. smartlist_free(circ->testing_cell_stats);
  932. circ->testing_cell_stats = NULL;
  933. }
  934. /** Deallocate space associated with circ.
  935. */
  936. STATIC void
  937. circuit_free_(circuit_t *circ)
  938. {
  939. circid_t n_circ_id = 0;
  940. void *mem;
  941. size_t memlen;
  942. int should_free = 1;
  943. if (!circ)
  944. return;
  945. /* We keep a copy of this so we can log its value before it gets unset. */
  946. n_circ_id = circ->n_circ_id;
  947. circuit_clear_testing_cell_stats(circ);
  948. /* Cleanup circuit from anything HS v3 related. We also do this when the
  949. * circuit is closed. This is to avoid any code path that free registered
  950. * circuits without closing them before. This needs to be done before the
  951. * hs identifier is freed. */
  952. hs_circ_cleanup(circ);
  953. if (CIRCUIT_IS_ORIGIN(circ)) {
  954. origin_circuit_t *ocirc = TO_ORIGIN_CIRCUIT(circ);
  955. mem = ocirc;
  956. memlen = sizeof(origin_circuit_t);
  957. tor_assert(circ->magic == ORIGIN_CIRCUIT_MAGIC);
  958. circuit_remove_from_origin_circuit_list(ocirc);
  959. if (ocirc->half_streams) {
  960. SMARTLIST_FOREACH_BEGIN(ocirc->half_streams, half_edge_t *,
  961. half_conn) {
  962. half_edge_free(half_conn);
  963. } SMARTLIST_FOREACH_END(half_conn);
  964. smartlist_free(ocirc->half_streams);
  965. }
  966. if (ocirc->build_state) {
  967. extend_info_free(ocirc->build_state->chosen_exit);
  968. circuit_free_cpath_node(ocirc->build_state->pending_final_cpath);
  969. cpath_ref_decref(ocirc->build_state->service_pending_final_cpath_ref);
  970. }
  971. tor_free(ocirc->build_state);
  972. /* Cancel before freeing, if we haven't already succeeded or failed. */
  973. if (ocirc->guard_state) {
  974. entry_guard_cancel(&ocirc->guard_state);
  975. }
  976. circuit_guard_state_free(ocirc->guard_state);
  977. circuit_clear_cpath(ocirc);
  978. crypto_pk_free(ocirc->intro_key);
  979. rend_data_free(ocirc->rend_data);
  980. /* Finally, free the identifier of the circuit and nullify it so multiple
  981. * cleanup will work. */
  982. hs_ident_circuit_free(ocirc->hs_ident);
  983. ocirc->hs_ident = NULL;
  984. tor_free(ocirc->dest_address);
  985. if (ocirc->socks_username) {
  986. memwipe(ocirc->socks_username, 0x12, ocirc->socks_username_len);
  987. tor_free(ocirc->socks_username);
  988. }
  989. if (ocirc->socks_password) {
  990. memwipe(ocirc->socks_password, 0x06, ocirc->socks_password_len);
  991. tor_free(ocirc->socks_password);
  992. }
  993. addr_policy_list_free(ocirc->prepend_policy);
  994. } else {
  995. or_circuit_t *ocirc = TO_OR_CIRCUIT(circ);
  996. /* Remember cell statistics for this circuit before deallocating. */
  997. if (get_options()->CellStatistics)
  998. rep_hist_buffer_stats_add_circ(circ, time(NULL));
  999. mem = ocirc;
  1000. memlen = sizeof(or_circuit_t);
  1001. tor_assert(circ->magic == OR_CIRCUIT_MAGIC);
  1002. should_free = (ocirc->workqueue_entry == NULL);
  1003. relay_crypto_clear(&ocirc->crypto);
  1004. if (ocirc->rend_splice) {
  1005. or_circuit_t *other = ocirc->rend_splice;
  1006. tor_assert(other->base_.magic == OR_CIRCUIT_MAGIC);
  1007. other->rend_splice = NULL;
  1008. }
  1009. /* remove from map. */
  1010. circuit_set_p_circid_chan(ocirc, 0, NULL);
  1011. /* Clear cell queue _after_ removing it from the map. Otherwise our
  1012. * "active" checks will be violated. */
  1013. cell_queue_clear(&ocirc->p_chan_cells);
  1014. }
  1015. extend_info_free(circ->n_hop);
  1016. tor_free(circ->n_chan_create_cell);
  1017. if (circ->global_circuitlist_idx != -1) {
  1018. int idx = circ->global_circuitlist_idx;
  1019. circuit_t *c2 = smartlist_get(global_circuitlist, idx);
  1020. tor_assert(c2 == circ);
  1021. smartlist_del(global_circuitlist, idx);
  1022. if (idx < smartlist_len(global_circuitlist)) {
  1023. c2 = smartlist_get(global_circuitlist, idx);
  1024. c2->global_circuitlist_idx = idx;
  1025. }
  1026. }
  1027. /* Remove from map. */
  1028. circuit_set_n_circid_chan(circ, 0, NULL);
  1029. /* Clear cell queue _after_ removing it from the map. Otherwise our
  1030. * "active" checks will be violated. */
  1031. cell_queue_clear(&circ->n_chan_cells);
  1032. log_info(LD_CIRC, "Circuit %u (id: %" PRIu32 ") has been freed.",
  1033. n_circ_id,
  1034. CIRCUIT_IS_ORIGIN(circ) ?
  1035. TO_ORIGIN_CIRCUIT(circ)->global_identifier : 0);
  1036. if (should_free) {
  1037. memwipe(mem, 0xAA, memlen); /* poison memory */
  1038. tor_free(mem);
  1039. } else {
  1040. /* If we made it here, this is an or_circuit_t that still has a pending
  1041. * cpuworker request which we weren't able to cancel. Instead, set up
  1042. * the magic value so that when the reply comes back, we'll know to discard
  1043. * the reply and free this structure.
  1044. */
  1045. memwipe(mem, 0xAA, memlen);
  1046. circ->magic = DEAD_CIRCUIT_MAGIC;
  1047. }
  1048. }
  1049. /** Deallocate the linked list circ-><b>cpath</b>, and remove the cpath from
  1050. * <b>circ</b>. */
  1051. void
  1052. circuit_clear_cpath(origin_circuit_t *circ)
  1053. {
  1054. crypt_path_t *victim, *head, *cpath;
  1055. head = cpath = circ->cpath;
  1056. if (!cpath)
  1057. return;
  1058. /* it's a circular list, so we have to notice when we've
  1059. * gone through it once. */
  1060. while (cpath->next && cpath->next != head) {
  1061. victim = cpath;
  1062. cpath = victim->next;
  1063. circuit_free_cpath_node(victim);
  1064. }
  1065. circuit_free_cpath_node(cpath);
  1066. circ->cpath = NULL;
  1067. }
  1068. /** Release all storage held by circuits. */
  1069. void
  1070. circuit_free_all(void)
  1071. {
  1072. smartlist_t *lst = circuit_get_global_list();
  1073. SMARTLIST_FOREACH_BEGIN(lst, circuit_t *, tmp) {
  1074. if (! CIRCUIT_IS_ORIGIN(tmp)) {
  1075. or_circuit_t *or_circ = TO_OR_CIRCUIT(tmp);
  1076. while (or_circ->resolving_streams) {
  1077. edge_connection_t *next_conn;
  1078. next_conn = or_circ->resolving_streams->next_stream;
  1079. connection_free_(TO_CONN(or_circ->resolving_streams));
  1080. or_circ->resolving_streams = next_conn;
  1081. }
  1082. }
  1083. tmp->global_circuitlist_idx = -1;
  1084. circuit_about_to_free_atexit(tmp);
  1085. circuit_free(tmp);
  1086. SMARTLIST_DEL_CURRENT(lst, tmp);
  1087. } SMARTLIST_FOREACH_END(tmp);
  1088. smartlist_free(lst);
  1089. global_circuitlist = NULL;
  1090. smartlist_free(global_origin_circuit_list);
  1091. global_origin_circuit_list = NULL;
  1092. smartlist_free(circuits_pending_chans);
  1093. circuits_pending_chans = NULL;
  1094. smartlist_free(circuits_pending_close);
  1095. circuits_pending_close = NULL;
  1096. smartlist_free(circuits_pending_other_guards);
  1097. circuits_pending_other_guards = NULL;
  1098. {
  1099. chan_circid_circuit_map_t **elt, **next, *c;
  1100. for (elt = HT_START(chan_circid_map, &chan_circid_map);
  1101. elt;
  1102. elt = next) {
  1103. c = *elt;
  1104. next = HT_NEXT_RMV(chan_circid_map, &chan_circid_map, elt);
  1105. tor_assert(c->circuit == NULL);
  1106. tor_free(c);
  1107. }
  1108. }
  1109. HT_CLEAR(chan_circid_map, &chan_circid_map);
  1110. }
  1111. /** Deallocate space associated with the cpath node <b>victim</b>. */
  1112. static void
  1113. circuit_free_cpath_node(crypt_path_t *victim)
  1114. {
  1115. if (!victim)
  1116. return;
  1117. relay_crypto_clear(&victim->crypto);
  1118. onion_handshake_state_release(&victim->handshake_state);
  1119. crypto_dh_free(victim->rend_dh_handshake_state);
  1120. extend_info_free(victim->extend_info);
  1121. memwipe(victim, 0xBB, sizeof(crypt_path_t)); /* poison memory */
  1122. tor_free(victim);
  1123. }
  1124. /** Release a crypt_path_reference_t*, which may be NULL. */
  1125. static void
  1126. cpath_ref_decref(crypt_path_reference_t *cpath_ref)
  1127. {
  1128. if (cpath_ref != NULL) {
  1129. if (--(cpath_ref->refcount) == 0) {
  1130. circuit_free_cpath_node(cpath_ref->cpath);
  1131. tor_free(cpath_ref);
  1132. }
  1133. }
  1134. }
  1135. /** A helper function for circuit_dump_by_conn() below. Log a bunch
  1136. * of information about circuit <b>circ</b>.
  1137. */
  1138. static void
  1139. circuit_dump_conn_details(int severity,
  1140. circuit_t *circ,
  1141. int conn_array_index,
  1142. const char *type,
  1143. circid_t this_circid,
  1144. circid_t other_circid)
  1145. {
  1146. tor_log(severity, LD_CIRC, "Conn %d has %s circuit: circID %u "
  1147. "(other side %u), state %d (%s), born %ld:",
  1148. conn_array_index, type, (unsigned)this_circid, (unsigned)other_circid,
  1149. circ->state, circuit_state_to_string(circ->state),
  1150. (long)circ->timestamp_began.tv_sec);
  1151. if (CIRCUIT_IS_ORIGIN(circ)) { /* circ starts at this node */
  1152. circuit_log_path(severity, LD_CIRC, TO_ORIGIN_CIRCUIT(circ));
  1153. }
  1154. }
  1155. /** Log, at severity <b>severity</b>, information about each circuit
  1156. * that is connected to <b>conn</b>.
  1157. */
  1158. void
  1159. circuit_dump_by_conn(connection_t *conn, int severity)
  1160. {
  1161. edge_connection_t *tmpconn;
  1162. SMARTLIST_FOREACH_BEGIN(circuit_get_global_list(), circuit_t *, circ) {
  1163. circid_t n_circ_id = circ->n_circ_id, p_circ_id = 0;
  1164. if (circ->marked_for_close) {
  1165. continue;
  1166. }
  1167. if (!CIRCUIT_IS_ORIGIN(circ)) {
  1168. p_circ_id = TO_OR_CIRCUIT(circ)->p_circ_id;
  1169. }
  1170. if (CIRCUIT_IS_ORIGIN(circ)) {
  1171. for (tmpconn=TO_ORIGIN_CIRCUIT(circ)->p_streams; tmpconn;
  1172. tmpconn=tmpconn->next_stream) {
  1173. if (TO_CONN(tmpconn) == conn) {
  1174. circuit_dump_conn_details(severity, circ, conn->conn_array_index,
  1175. "App-ward", p_circ_id, n_circ_id);
  1176. }
  1177. }
  1178. }
  1179. if (! CIRCUIT_IS_ORIGIN(circ)) {
  1180. for (tmpconn=TO_OR_CIRCUIT(circ)->n_streams; tmpconn;
  1181. tmpconn=tmpconn->next_stream) {
  1182. if (TO_CONN(tmpconn) == conn) {
  1183. circuit_dump_conn_details(severity, circ, conn->conn_array_index,
  1184. "Exit-ward", n_circ_id, p_circ_id);
  1185. }
  1186. }
  1187. }
  1188. }
  1189. SMARTLIST_FOREACH_END(circ);
  1190. }
  1191. /** Return the circuit whose global ID is <b>id</b>, or NULL if no
  1192. * such circuit exists. */
  1193. origin_circuit_t *
  1194. circuit_get_by_global_id(uint32_t id)
  1195. {
  1196. SMARTLIST_FOREACH_BEGIN(circuit_get_global_list(), circuit_t *, circ) {
  1197. if (CIRCUIT_IS_ORIGIN(circ) &&
  1198. TO_ORIGIN_CIRCUIT(circ)->global_identifier == id) {
  1199. if (circ->marked_for_close)
  1200. return NULL;
  1201. else
  1202. return TO_ORIGIN_CIRCUIT(circ);
  1203. }
  1204. }
  1205. SMARTLIST_FOREACH_END(circ);
  1206. return NULL;
  1207. }
  1208. /** Return a circ such that:
  1209. * - circ-\>n_circ_id or circ-\>p_circ_id is equal to <b>circ_id</b>, and
  1210. * - circ is attached to <b>chan</b>, either as p_chan or n_chan.
  1211. * Return NULL if no such circuit exists.
  1212. *
  1213. * If <b>found_entry_out</b> is provided, set it to true if we have a
  1214. * placeholder entry for circid/chan, and leave it unset otherwise.
  1215. */
  1216. static inline circuit_t *
  1217. circuit_get_by_circid_channel_impl(circid_t circ_id, channel_t *chan,
  1218. int *found_entry_out)
  1219. {
  1220. chan_circid_circuit_map_t search;
  1221. chan_circid_circuit_map_t *found;
  1222. if (_last_circid_chan_ent &&
  1223. circ_id == _last_circid_chan_ent->circ_id &&
  1224. chan == _last_circid_chan_ent->chan) {
  1225. found = _last_circid_chan_ent;
  1226. } else {
  1227. search.circ_id = circ_id;
  1228. search.chan = chan;
  1229. found = HT_FIND(chan_circid_map, &chan_circid_map, &search);
  1230. _last_circid_chan_ent = found;
  1231. }
  1232. if (found && found->circuit) {
  1233. log_debug(LD_CIRC,
  1234. "circuit_get_by_circid_channel_impl() returning circuit %p for"
  1235. " circ_id %u, channel ID %"PRIu64 " (%p)",
  1236. found->circuit, (unsigned)circ_id,
  1237. (chan->global_identifier), chan);
  1238. if (found_entry_out)
  1239. *found_entry_out = 1;
  1240. return found->circuit;
  1241. }
  1242. log_debug(LD_CIRC,
  1243. "circuit_get_by_circid_channel_impl() found %s for"
  1244. " circ_id %u, channel ID %"PRIu64 " (%p)",
  1245. found ? "placeholder" : "nothing",
  1246. (unsigned)circ_id,
  1247. (chan->global_identifier), chan);
  1248. if (found_entry_out)
  1249. *found_entry_out = found ? 1 : 0;
  1250. return NULL;
  1251. /* The rest of this checks for bugs. Disabled by default. */
  1252. /* We comment it out because coverity complains otherwise.
  1253. {
  1254. circuit_t *circ;
  1255. TOR_LIST_FOREACH(circ, &global_circuitlist, head) {
  1256. if (! CIRCUIT_IS_ORIGIN(circ)) {
  1257. or_circuit_t *or_circ = TO_OR_CIRCUIT(circ);
  1258. if (or_circ->p_chan == chan && or_circ->p_circ_id == circ_id) {
  1259. log_warn(LD_BUG,
  1260. "circuit matches p_chan, but not in hash table (Bug!)");
  1261. return circ;
  1262. }
  1263. }
  1264. if (circ->n_chan == chan && circ->n_circ_id == circ_id) {
  1265. log_warn(LD_BUG,
  1266. "circuit matches n_chan, but not in hash table (Bug!)");
  1267. return circ;
  1268. }
  1269. }
  1270. return NULL;
  1271. } */
  1272. }
  1273. /** Return a circ such that:
  1274. * - circ-\>n_circ_id or circ-\>p_circ_id is equal to <b>circ_id</b>, and
  1275. * - circ is attached to <b>chan</b>, either as p_chan or n_chan.
  1276. * - circ is not marked for close.
  1277. * Return NULL if no such circuit exists.
  1278. */
  1279. circuit_t *
  1280. circuit_get_by_circid_channel(circid_t circ_id, channel_t *chan)
  1281. {
  1282. circuit_t *circ = circuit_get_by_circid_channel_impl(circ_id, chan, NULL);
  1283. if (!circ || circ->marked_for_close)
  1284. return NULL;
  1285. else
  1286. return circ;
  1287. }
  1288. /** Return a circ such that:
  1289. * - circ-\>n_circ_id or circ-\>p_circ_id is equal to <b>circ_id</b>, and
  1290. * - circ is attached to <b>chan</b>, either as p_chan or n_chan.
  1291. * Return NULL if no such circuit exists.
  1292. */
  1293. circuit_t *
  1294. circuit_get_by_circid_channel_even_if_marked(circid_t circ_id,
  1295. channel_t *chan)
  1296. {
  1297. return circuit_get_by_circid_channel_impl(circ_id, chan, NULL);
  1298. }
  1299. /** Return true iff the circuit ID <b>circ_id</b> is currently used by a
  1300. * circuit, marked or not, on <b>chan</b>, or if the circ ID is reserved until
  1301. * a queued destroy cell can be sent.
  1302. *
  1303. * (Return 1 if the circuit is present, marked or not; Return 2
  1304. * if the circuit ID is pending a destroy.)
  1305. **/
  1306. int
  1307. circuit_id_in_use_on_channel(circid_t circ_id, channel_t *chan)
  1308. {
  1309. int found = 0;
  1310. if (circuit_get_by_circid_channel_impl(circ_id, chan, &found) != NULL)
  1311. return 1;
  1312. if (found)
  1313. return 2;
  1314. return 0;
  1315. }
  1316. /** Helper for debugging 12184. Returns the time since which 'circ_id' has
  1317. * been marked unusable on 'chan'. */
  1318. time_t
  1319. circuit_id_when_marked_unusable_on_channel(circid_t circ_id, channel_t *chan)
  1320. {
  1321. chan_circid_circuit_map_t search;
  1322. chan_circid_circuit_map_t *found;
  1323. memset(&search, 0, sizeof(search));
  1324. search.circ_id = circ_id;
  1325. search.chan = chan;
  1326. found = HT_FIND(chan_circid_map, &chan_circid_map, &search);
  1327. if (! found || found->circuit)
  1328. return 0;
  1329. return found->made_placeholder_at;
  1330. }
  1331. /** Return the circuit that a given edge connection is using. */
  1332. circuit_t *
  1333. circuit_get_by_edge_conn(edge_connection_t *conn)
  1334. {
  1335. circuit_t *circ;
  1336. circ = conn->on_circuit;
  1337. tor_assert(!circ ||
  1338. (CIRCUIT_IS_ORIGIN(circ) ? circ->magic == ORIGIN_CIRCUIT_MAGIC
  1339. : circ->magic == OR_CIRCUIT_MAGIC));
  1340. return circ;
  1341. }
  1342. /** For each circuit that has <b>chan</b> as n_chan or p_chan, unlink the
  1343. * circuit from the chan,circid map, and mark it for close if it hasn't
  1344. * been marked already.
  1345. */
  1346. void
  1347. circuit_unlink_all_from_channel(channel_t *chan, int reason)
  1348. {
  1349. smartlist_t *detached = smartlist_new();
  1350. /* #define DEBUG_CIRCUIT_UNLINK_ALL */
  1351. channel_unlink_all_circuits(chan, detached);
  1352. #ifdef DEBUG_CIRCUIT_UNLINK_ALL
  1353. {
  1354. smartlist_t *detached_2 = smartlist_new();
  1355. int mismatch = 0, badlen = 0;
  1356. SMARTLIST_FOREACH_BEGIN(circuit_get_global_list(), circuit_t *, circ) {
  1357. if (circ->n_chan == chan ||
  1358. (!CIRCUIT_IS_ORIGIN(circ) &&
  1359. TO_OR_CIRCUIT(circ)->p_chan == chan)) {
  1360. smartlist_add(detached_2, circ);
  1361. }
  1362. }
  1363. SMARTLIST_FOREACH_END(circ);
  1364. if (smartlist_len(detached) != smartlist_len(detached_2)) {
  1365. log_warn(LD_BUG, "List of detached circuits had the wrong length! "
  1366. "(got %d, should have gotten %d)",
  1367. (int)smartlist_len(detached),
  1368. (int)smartlist_len(detached_2));
  1369. badlen = 1;
  1370. }
  1371. smartlist_sort_pointers(detached);
  1372. smartlist_sort_pointers(detached_2);
  1373. SMARTLIST_FOREACH(detached, circuit_t *, c,
  1374. if (c != smartlist_get(detached_2, c_sl_idx))
  1375. mismatch = 1;
  1376. );
  1377. if (mismatch)
  1378. log_warn(LD_BUG, "Mismatch in list of detached circuits.");
  1379. if (badlen || mismatch) {
  1380. smartlist_free(detached);
  1381. detached = detached_2;
  1382. } else {
  1383. log_notice(LD_CIRC, "List of %d circuits was as expected.",
  1384. (int)smartlist_len(detached));
  1385. smartlist_free(detached_2);
  1386. }
  1387. }
  1388. #endif /* defined(DEBUG_CIRCUIT_UNLINK_ALL) */
  1389. SMARTLIST_FOREACH_BEGIN(detached, circuit_t *, circ) {
  1390. int mark = 0;
  1391. if (circ->n_chan == chan) {
  1392. circuit_set_n_circid_chan(circ, 0, NULL);
  1393. mark = 1;
  1394. /* If we didn't request this closure, pass the remote
  1395. * bit to mark_for_close. */
  1396. if (chan->reason_for_closing != CHANNEL_CLOSE_REQUESTED)
  1397. reason |= END_CIRC_REASON_FLAG_REMOTE;
  1398. }
  1399. if (! CIRCUIT_IS_ORIGIN(circ)) {
  1400. or_circuit_t *or_circ = TO_OR_CIRCUIT(circ);
  1401. if (or_circ->p_chan == chan) {
  1402. circuit_set_p_circid_chan(or_circ, 0, NULL);
  1403. mark = 1;
  1404. }
  1405. }
  1406. if (!mark) {
  1407. log_warn(LD_BUG, "Circuit on detached list which I had no reason "
  1408. "to mark");
  1409. continue;
  1410. }
  1411. if (!circ->marked_for_close)
  1412. circuit_mark_for_close(circ, reason);
  1413. } SMARTLIST_FOREACH_END(circ);
  1414. smartlist_free(detached);
  1415. }
  1416. /** Return a circ such that
  1417. * - circ-\>rend_data-\>onion_address is equal to
  1418. * <b>rend_data</b>-\>onion_address,
  1419. * - circ-\>rend_data-\>rend_cookie is equal to
  1420. * <b>rend_data</b>-\>rend_cookie, and
  1421. * - circ-\>purpose is equal to CIRCUIT_PURPOSE_C_REND_READY.
  1422. *
  1423. * Return NULL if no such circuit exists.
  1424. */
  1425. origin_circuit_t *
  1426. circuit_get_ready_rend_circ_by_rend_data(const rend_data_t *rend_data)
  1427. {
  1428. SMARTLIST_FOREACH_BEGIN(circuit_get_global_list(), circuit_t *, circ) {
  1429. if (!circ->marked_for_close &&
  1430. circ->purpose == CIRCUIT_PURPOSE_C_REND_READY) {
  1431. origin_circuit_t *ocirc = TO_ORIGIN_CIRCUIT(circ);
  1432. if (ocirc->rend_data == NULL) {
  1433. continue;
  1434. }
  1435. if (!rend_cmp_service_ids(rend_data_get_address(rend_data),
  1436. rend_data_get_address(ocirc->rend_data)) &&
  1437. tor_memeq(ocirc->rend_data->rend_cookie,
  1438. rend_data->rend_cookie,
  1439. REND_COOKIE_LEN))
  1440. return ocirc;
  1441. }
  1442. }
  1443. SMARTLIST_FOREACH_END(circ);
  1444. return NULL;
  1445. }
  1446. /** Return the first service introduction circuit originating from the global
  1447. * circuit list after <b>start</b> or at the start of the list if <b>start</b>
  1448. * is NULL. Return NULL if no circuit is found.
  1449. *
  1450. * A service introduction point circuit has a purpose of either
  1451. * CIRCUIT_PURPOSE_S_ESTABLISH_INTRO or CIRCUIT_PURPOSE_S_INTRO. This does not
  1452. * return a circuit marked for close and its state must be open. */
  1453. origin_circuit_t *
  1454. circuit_get_next_service_intro_circ(origin_circuit_t *start)
  1455. {
  1456. int idx = 0;
  1457. smartlist_t *lst = circuit_get_global_list();
  1458. if (start) {
  1459. idx = TO_CIRCUIT(start)->global_circuitlist_idx + 1;
  1460. }
  1461. for ( ; idx < smartlist_len(lst); ++idx) {
  1462. circuit_t *circ = smartlist_get(lst, idx);
  1463. /* Ignore a marked for close circuit or purpose not matching a service
  1464. * intro point or if the state is not open. */
  1465. if (circ->marked_for_close || circ->state != CIRCUIT_STATE_OPEN ||
  1466. (circ->purpose != CIRCUIT_PURPOSE_S_ESTABLISH_INTRO &&
  1467. circ->purpose != CIRCUIT_PURPOSE_S_INTRO)) {
  1468. continue;
  1469. }
  1470. /* The purposes we are looking for are only for origin circuits so the
  1471. * following is valid. */
  1472. return TO_ORIGIN_CIRCUIT(circ);
  1473. }
  1474. /* Not found. */
  1475. return NULL;
  1476. }
  1477. /** Return the first service rendezvous circuit originating from the global
  1478. * circuit list after <b>start</b> or at the start of the list if <b>start</b>
  1479. * is NULL. Return NULL if no circuit is found.
  1480. *
  1481. * A service rendezvous point circuit has a purpose of either
  1482. * CIRCUIT_PURPOSE_S_CONNECT_REND or CIRCUIT_PURPOSE_S_REND_JOINED. This does
  1483. * not return a circuit marked for close and its state must be open. */
  1484. origin_circuit_t *
  1485. circuit_get_next_service_rp_circ(origin_circuit_t *start)
  1486. {
  1487. int idx = 0;
  1488. smartlist_t *lst = circuit_get_global_list();
  1489. if (start) {
  1490. idx = TO_CIRCUIT(start)->global_circuitlist_idx + 1;
  1491. }
  1492. for ( ; idx < smartlist_len(lst); ++idx) {
  1493. circuit_t *circ = smartlist_get(lst, idx);
  1494. /* Ignore a marked for close circuit or purpose not matching a service
  1495. * intro point or if the state is not open. */
  1496. if (circ->marked_for_close || circ->state != CIRCUIT_STATE_OPEN ||
  1497. (circ->purpose != CIRCUIT_PURPOSE_S_CONNECT_REND &&
  1498. circ->purpose != CIRCUIT_PURPOSE_S_REND_JOINED)) {
  1499. continue;
  1500. }
  1501. /* The purposes we are looking for are only for origin circuits so the
  1502. * following is valid. */
  1503. return TO_ORIGIN_CIRCUIT(circ);
  1504. }
  1505. /* Not found. */
  1506. return NULL;
  1507. }
  1508. /** Return the first circuit originating here in global_circuitlist after
  1509. * <b>start</b> whose purpose is <b>purpose</b>, and where <b>digest</b> (if
  1510. * set) matches the private key digest of the rend data associated with the
  1511. * circuit. Return NULL if no circuit is found. If <b>start</b> is NULL,
  1512. * begin at the start of the list.
  1513. */
  1514. origin_circuit_t *
  1515. circuit_get_next_by_pk_and_purpose(origin_circuit_t *start,
  1516. const uint8_t *digest, uint8_t purpose)
  1517. {
  1518. int idx;
  1519. smartlist_t *lst = circuit_get_global_list();
  1520. tor_assert(CIRCUIT_PURPOSE_IS_ORIGIN(purpose));
  1521. if (start == NULL)
  1522. idx = 0;
  1523. else
  1524. idx = TO_CIRCUIT(start)->global_circuitlist_idx + 1;
  1525. for ( ; idx < smartlist_len(lst); ++idx) {
  1526. circuit_t *circ = smartlist_get(lst, idx);
  1527. origin_circuit_t *ocirc;
  1528. if (circ->marked_for_close)
  1529. continue;
  1530. if (circ->purpose != purpose)
  1531. continue;
  1532. /* At this point we should be able to get a valid origin circuit because
  1533. * the origin purpose we are looking for matches this circuit. */
  1534. if (BUG(!CIRCUIT_PURPOSE_IS_ORIGIN(circ->purpose))) {
  1535. break;
  1536. }
  1537. ocirc = TO_ORIGIN_CIRCUIT(circ);
  1538. if (!digest)
  1539. return ocirc;
  1540. if (rend_circuit_pk_digest_eq(ocirc, digest)) {
  1541. return ocirc;
  1542. }
  1543. }
  1544. return NULL;
  1545. }
  1546. /** We might cannibalize this circuit: Return true if its last hop can be used
  1547. * as a v3 rendezvous point. */
  1548. static int
  1549. circuit_can_be_cannibalized_for_v3_rp(const origin_circuit_t *circ)
  1550. {
  1551. if (!circ->build_state) {
  1552. return 0;
  1553. }
  1554. extend_info_t *chosen_exit = circ->build_state->chosen_exit;
  1555. if (BUG(!chosen_exit)) {
  1556. return 0;
  1557. }
  1558. const node_t *rp_node = node_get_by_id(chosen_exit->identity_digest);
  1559. if (rp_node) {
  1560. if (node_supports_v3_rendezvous_point(rp_node)) {
  1561. return 1;
  1562. }
  1563. }
  1564. return 0;
  1565. }
  1566. /** We are trying to create a circuit of purpose <b>purpose</b> and we are
  1567. * looking for cannibalizable circuits. Return the circuit purpose we would be
  1568. * willing to cannibalize. */
  1569. static uint8_t
  1570. get_circuit_purpose_needed_to_cannibalize(uint8_t purpose)
  1571. {
  1572. if (circuit_should_use_vanguards(purpose)) {
  1573. /* If we are using vanguards, then we should only cannibalize vanguard
  1574. * circuits so that we get the same path construction logic. */
  1575. return CIRCUIT_PURPOSE_HS_VANGUARDS;
  1576. } else {
  1577. /* If no vanguards are used just get a general circuit! */
  1578. return CIRCUIT_PURPOSE_C_GENERAL;
  1579. }
  1580. }
  1581. /** Return a circuit that is open, is CIRCUIT_PURPOSE_C_GENERAL,
  1582. * has a timestamp_dirty value of 0, has flags matching the CIRCLAUNCH_*
  1583. * flags in <b>flags</b>, and if info is defined, does not already use info
  1584. * as any of its hops; or NULL if no circuit fits this description.
  1585. *
  1586. * The <b>purpose</b> argument refers to the purpose of the circuit we want to
  1587. * create, not the purpose of the circuit we want to cannibalize.
  1588. *
  1589. * If !CIRCLAUNCH_NEED_UPTIME, prefer returning non-uptime circuits.
  1590. *
  1591. * To "cannibalize" a circuit means to extend it an extra hop, and use it
  1592. * for some other purpose than we had originally intended. We do this when
  1593. * we want to perform some low-bandwidth task at a specific relay, and we
  1594. * would like the circuit to complete as soon as possible. (If we were going
  1595. * to use a lot of bandwidth, we wouldn't want a circuit with an extra hop.
  1596. * If we didn't care about circuit completion latency, we would just build
  1597. * a new circuit.)
  1598. */
  1599. origin_circuit_t *
  1600. circuit_find_to_cannibalize(uint8_t purpose_to_produce, extend_info_t *info,
  1601. int flags)
  1602. {
  1603. origin_circuit_t *best=NULL;
  1604. int need_uptime = (flags & CIRCLAUNCH_NEED_UPTIME) != 0;
  1605. int need_capacity = (flags & CIRCLAUNCH_NEED_CAPACITY) != 0;
  1606. int internal = (flags & CIRCLAUNCH_IS_INTERNAL) != 0;
  1607. const or_options_t *options = get_options();
  1608. /* We want the circuit we are trying to cannibalize to have this purpose */
  1609. int purpose_to_search_for;
  1610. /* Make sure we're not trying to create a onehop circ by
  1611. * cannibalization. */
  1612. tor_assert(!(flags & CIRCLAUNCH_ONEHOP_TUNNEL));
  1613. purpose_to_search_for = get_circuit_purpose_needed_to_cannibalize(
  1614. purpose_to_produce);
  1615. tor_assert_nonfatal(purpose_to_search_for == CIRCUIT_PURPOSE_C_GENERAL ||
  1616. purpose_to_search_for == CIRCUIT_PURPOSE_HS_VANGUARDS);
  1617. log_debug(LD_CIRC,
  1618. "Hunting for a circ to cannibalize: purpose %d, uptime %d, "
  1619. "capacity %d, internal %d",
  1620. purpose_to_produce, need_uptime, need_capacity, internal);
  1621. SMARTLIST_FOREACH_BEGIN(circuit_get_global_list(), circuit_t *, circ_) {
  1622. if (CIRCUIT_IS_ORIGIN(circ_) &&
  1623. circ_->state == CIRCUIT_STATE_OPEN &&
  1624. !circ_->marked_for_close &&
  1625. circ_->purpose == purpose_to_search_for &&
  1626. !circ_->timestamp_dirty) {
  1627. origin_circuit_t *circ = TO_ORIGIN_CIRCUIT(circ_);
  1628. /* Only cannibalize from reasonable length circuits. If we
  1629. * want C_GENERAL, then only choose 3 hop circs. If we want
  1630. * HS_VANGUARDS, only choose 4 hop circs.
  1631. */
  1632. if (circ->build_state->desired_path_len !=
  1633. route_len_for_purpose(purpose_to_search_for, NULL)) {
  1634. goto next;
  1635. }
  1636. /* Ignore any circuits for which we can't use the Guard. It is possible
  1637. * that the Guard was removed from the samepled set after the circuit
  1638. * was created so avoid using it. */
  1639. if (!entry_guard_could_succeed(circ->guard_state)) {
  1640. goto next;
  1641. }
  1642. if ((!need_uptime || circ->build_state->need_uptime) &&
  1643. (!need_capacity || circ->build_state->need_capacity) &&
  1644. (internal == circ->build_state->is_internal) &&
  1645. !circ->unusable_for_new_conns &&
  1646. circ->remaining_relay_early_cells &&
  1647. !circ->build_state->onehop_tunnel &&
  1648. !circ->isolation_values_set) {
  1649. if (info) {
  1650. /* need to make sure we don't duplicate hops */
  1651. crypt_path_t *hop = circ->cpath;
  1652. const node_t *ri1 = node_get_by_id(info->identity_digest);
  1653. do {
  1654. const node_t *ri2;
  1655. if (tor_memeq(hop->extend_info->identity_digest,
  1656. info->identity_digest, DIGEST_LEN))
  1657. goto next;
  1658. if (ri1 &&
  1659. (ri2 = node_get_by_id(hop->extend_info->identity_digest))
  1660. && nodes_in_same_family(ri1, ri2))
  1661. goto next;
  1662. hop=hop->next;
  1663. } while (hop!=circ->cpath);
  1664. }
  1665. if (options->ExcludeNodes) {
  1666. /* Make sure no existing nodes in the circuit are excluded for
  1667. * general use. (This may be possible if StrictNodes is 0, and we
  1668. * thought we needed to use an otherwise excluded node for, say, a
  1669. * directory operation.) */
  1670. crypt_path_t *hop = circ->cpath;
  1671. do {
  1672. if (routerset_contains_extendinfo(options->ExcludeNodes,
  1673. hop->extend_info))
  1674. goto next;
  1675. hop = hop->next;
  1676. } while (hop != circ->cpath);
  1677. }
  1678. if ((flags & CIRCLAUNCH_IS_V3_RP) &&
  1679. !circuit_can_be_cannibalized_for_v3_rp(circ)) {
  1680. log_debug(LD_GENERAL, "Skipping uncannibalizable circuit for v3 "
  1681. "rendezvous point.");
  1682. goto next;
  1683. }
  1684. if (!best || (best->build_state->need_uptime && !need_uptime))
  1685. best = circ;
  1686. next: ;
  1687. }
  1688. }
  1689. }
  1690. SMARTLIST_FOREACH_END(circ_);
  1691. return best;
  1692. }
  1693. /**
  1694. * Check whether any of the origin circuits that are waiting to see if
  1695. * their guard is good enough to use can be upgraded to "ready". If so,
  1696. * return a new smartlist containing them. Otherwise return NULL.
  1697. */
  1698. smartlist_t *
  1699. circuit_find_circuits_to_upgrade_from_guard_wait(void)
  1700. {
  1701. /* Only if some circuit is actually waiting on an upgrade should we
  1702. * run the algorithm. */
  1703. if (! circuits_pending_other_guards ||
  1704. smartlist_len(circuits_pending_other_guards)==0)
  1705. return NULL;
  1706. /* Only if we have some origin circuits should we run the algorithm. */
  1707. if (!global_origin_circuit_list)
  1708. return NULL;
  1709. /* Okay; we can pass our circuit list to entrynodes.c.*/
  1710. smartlist_t *result = smartlist_new();
  1711. int circuits_upgraded = entry_guards_upgrade_waiting_circuits(
  1712. get_guard_selection_info(),
  1713. global_origin_circuit_list,
  1714. result);
  1715. if (circuits_upgraded && smartlist_len(result)) {
  1716. return result;
  1717. } else {
  1718. smartlist_free(result);
  1719. return NULL;
  1720. }
  1721. }
  1722. /** Return the number of hops in circuit's path. If circ has no entries,
  1723. * or is NULL, returns 0. */
  1724. int
  1725. circuit_get_cpath_len(origin_circuit_t *circ)
  1726. {
  1727. int n = 0;
  1728. if (circ && circ->cpath) {
  1729. crypt_path_t *cpath, *cpath_next = NULL;
  1730. for (cpath = circ->cpath; cpath_next != circ->cpath; cpath = cpath_next) {
  1731. cpath_next = cpath->next;
  1732. ++n;
  1733. }
  1734. }
  1735. return n;
  1736. }
  1737. /** Return the number of opened hops in circuit's path.
  1738. * If circ has no entries, or is NULL, returns 0. */
  1739. int
  1740. circuit_get_cpath_opened_len(const origin_circuit_t *circ)
  1741. {
  1742. int n = 0;
  1743. if (circ && circ->cpath) {
  1744. crypt_path_t *cpath, *cpath_next = NULL;
  1745. for (cpath = circ->cpath;
  1746. cpath->state == CPATH_STATE_OPEN
  1747. && cpath_next != circ->cpath;
  1748. cpath = cpath_next) {
  1749. cpath_next = cpath->next;
  1750. ++n;
  1751. }
  1752. }
  1753. return n;
  1754. }
  1755. /** Return the <b>hopnum</b>th hop in <b>circ</b>->cpath, or NULL if there
  1756. * aren't that many hops in the list. <b>hopnum</b> starts at 1.
  1757. * Returns NULL if <b>hopnum</b> is 0 or negative. */
  1758. crypt_path_t *
  1759. circuit_get_cpath_hop(origin_circuit_t *circ, int hopnum)
  1760. {
  1761. if (circ && circ->cpath && hopnum > 0) {
  1762. crypt_path_t *cpath, *cpath_next = NULL;
  1763. for (cpath = circ->cpath; cpath_next != circ->cpath; cpath = cpath_next) {
  1764. cpath_next = cpath->next;
  1765. if (--hopnum <= 0)
  1766. return cpath;
  1767. }
  1768. }
  1769. return NULL;
  1770. }
  1771. /** Go through the circuitlist; mark-for-close each circuit that starts
  1772. * at us but has not yet been used. */
  1773. void
  1774. circuit_mark_all_unused_circs(void)
  1775. {
  1776. SMARTLIST_FOREACH_BEGIN(circuit_get_global_list(), circuit_t *, circ) {
  1777. if (CIRCUIT_IS_ORIGIN(circ) &&
  1778. !circ->marked_for_close &&
  1779. !circ->timestamp_dirty)
  1780. circuit_mark_for_close(circ, END_CIRC_REASON_FINISHED);
  1781. }
  1782. SMARTLIST_FOREACH_END(circ);
  1783. }
  1784. /** Go through the circuitlist; for each circuit that starts at us
  1785. * and is dirty, frob its timestamp_dirty so we won't use it for any
  1786. * new streams.
  1787. *
  1788. * This is useful for letting the user change pseudonyms, so new
  1789. * streams will not be linkable to old streams.
  1790. */
  1791. void
  1792. circuit_mark_all_dirty_circs_as_unusable(void)
  1793. {
  1794. SMARTLIST_FOREACH_BEGIN(circuit_get_global_list(), circuit_t *, circ) {
  1795. if (CIRCUIT_IS_ORIGIN(circ) &&
  1796. !circ->marked_for_close &&
  1797. circ->timestamp_dirty) {
  1798. mark_circuit_unusable_for_new_conns(TO_ORIGIN_CIRCUIT(circ));
  1799. }
  1800. }
  1801. SMARTLIST_FOREACH_END(circ);
  1802. }
  1803. /**
  1804. * Report any queued cells on or_circuits as written in our bandwidth
  1805. * totals, for the specified channel direction.
  1806. *
  1807. * When we close a circuit or clear its cell queues, we've read
  1808. * data and recorded those bytes in our read statistics, but we're
  1809. * not going to write it. This discrepancy can be used by an adversary
  1810. * to infer information from our public relay statistics and perform
  1811. * attacks such as guard discovery.
  1812. *
  1813. * This function is in the critical path of circuit_mark_for_close().
  1814. * It must be (and is) O(1)!
  1815. *
  1816. * See https://trac.torproject.org/projects/tor/ticket/23512.
  1817. */
  1818. void
  1819. circuit_synchronize_written_or_bandwidth(const circuit_t *c,
  1820. circuit_channel_direction_t dir)
  1821. {
  1822. uint64_t cells;
  1823. uint64_t cell_size;
  1824. uint64_t written_sync;
  1825. const channel_t *chan = NULL;
  1826. const or_circuit_t *or_circ;
  1827. if (!CIRCUIT_IS_ORCIRC(c))
  1828. return;
  1829. or_circ = CONST_TO_OR_CIRCUIT(c);
  1830. if (dir == CIRCUIT_N_CHAN) {
  1831. chan = c->n_chan;
  1832. cells = c->n_chan_cells.n;
  1833. } else {
  1834. chan = or_circ->p_chan;
  1835. cells = or_circ->p_chan_cells.n;
  1836. }
  1837. /* If we still know the chan, determine real cell size. Otherwise,
  1838. * assume it's a wide circid channel */
  1839. if (chan)
  1840. cell_size = get_cell_network_size(chan->wide_circ_ids);
  1841. else
  1842. cell_size = CELL_MAX_NETWORK_SIZE;
  1843. /* The missing written bytes are the cell counts times their cell
  1844. * size plus TLS per cell overhead */
  1845. written_sync = cells*(cell_size+TLS_PER_CELL_OVERHEAD);
  1846. /* Report the missing bytes as written, to avoid asymmetry.
  1847. * We must use time() for consistency with rephist, even though on
  1848. * some very old rare platforms, approx_time() may be faster. */
  1849. rep_hist_note_bytes_written(written_sync, time(NULL));
  1850. }
  1851. /** Mark <b>circ</b> to be closed next time we call
  1852. * circuit_close_all_marked(). Do any cleanup needed:
  1853. * - If state is onionskin_pending, remove circ from the onion_pending
  1854. * list.
  1855. * - If circ isn't open yet: call circuit_build_failed() if we're
  1856. * the origin.
  1857. * - If purpose is C_INTRODUCE_ACK_WAIT, report the intro point
  1858. * failure we just had to the hidden service client module.
  1859. * - If purpose is C_INTRODUCING and <b>reason</b> isn't TIMEOUT,
  1860. * report to the hidden service client module that the intro point
  1861. * we just tried may be unreachable.
  1862. * - Send appropriate destroys and edge_destroys for conns and
  1863. * streams attached to circ.
  1864. * - If circ->rend_splice is set (we are the midpoint of a joined
  1865. * rendezvous stream), then mark the other circuit to close as well.
  1866. */
  1867. MOCK_IMPL(void,
  1868. circuit_mark_for_close_, (circuit_t *circ, int reason, int line,
  1869. const char *file))
  1870. {
  1871. int orig_reason = reason; /* Passed to the controller */
  1872. assert_circuit_ok(circ);
  1873. tor_assert(line);
  1874. tor_assert(file);
  1875. if (circ->marked_for_close) {
  1876. log_warn(LD_BUG,
  1877. "Duplicate call to circuit_mark_for_close at %s:%d"
  1878. " (first at %s:%d)", file, line,
  1879. circ->marked_for_close_file, circ->marked_for_close);
  1880. return;
  1881. }
  1882. if (reason == END_CIRC_AT_ORIGIN) {
  1883. if (!CIRCUIT_IS_ORIGIN(circ)) {
  1884. log_warn(LD_BUG, "Specified 'at-origin' non-reason for ending circuit, "
  1885. "but circuit was not at origin. (called %s:%d, purpose=%d)",
  1886. file, line, circ->purpose);
  1887. }
  1888. reason = END_CIRC_REASON_NONE;
  1889. }
  1890. if (CIRCUIT_IS_ORIGIN(circ)) {
  1891. if (pathbias_check_close(TO_ORIGIN_CIRCUIT(circ), reason) == -1) {
  1892. /* Don't close it yet, we need to test it first */
  1893. return;
  1894. }
  1895. /* We don't send reasons when closing circuits at the origin. */
  1896. reason = END_CIRC_REASON_NONE;
  1897. }
  1898. circuit_synchronize_written_or_bandwidth(circ, CIRCUIT_N_CHAN);
  1899. circuit_synchronize_written_or_bandwidth(circ, CIRCUIT_P_CHAN);
  1900. if (reason & END_CIRC_REASON_FLAG_REMOTE)
  1901. reason &= ~END_CIRC_REASON_FLAG_REMOTE;
  1902. if (reason < END_CIRC_REASON_MIN_ || reason > END_CIRC_REASON_MAX_) {
  1903. if (!(orig_reason & END_CIRC_REASON_FLAG_REMOTE))
  1904. log_warn(LD_BUG, "Reason %d out of range at %s:%d", reason, file, line);
  1905. reason = END_CIRC_REASON_NONE;
  1906. }
  1907. circ->marked_for_close = line;
  1908. circ->marked_for_close_file = file;
  1909. circ->marked_for_close_reason = reason;
  1910. circ->marked_for_close_orig_reason = orig_reason;
  1911. if (!CIRCUIT_IS_ORIGIN(circ)) {
  1912. or_circuit_t *or_circ = TO_OR_CIRCUIT(circ);
  1913. if (or_circ->rend_splice) {
  1914. if (!or_circ->rend_splice->base_.marked_for_close) {
  1915. /* do this after marking this circuit, to avoid infinite recursion. */
  1916. circuit_mark_for_close(TO_CIRCUIT(or_circ->rend_splice), reason);
  1917. }
  1918. or_circ->rend_splice = NULL;
  1919. }
  1920. }
  1921. /* Notify the HS subsystem that this circuit is closing. */
  1922. hs_circ_cleanup(circ);
  1923. if (circuits_pending_close == NULL)
  1924. circuits_pending_close = smartlist_new();
  1925. smartlist_add(circuits_pending_close, circ);
  1926. mainloop_schedule_postloop_cleanup();
  1927. log_info(LD_GENERAL, "Circuit %u (id: %" PRIu32 ") marked for close at "
  1928. "%s:%d (orig reason: %d, new reason: %d)",
  1929. circ->n_circ_id,
  1930. CIRCUIT_IS_ORIGIN(circ) ?
  1931. TO_ORIGIN_CIRCUIT(circ)->global_identifier : 0,
  1932. file, line, orig_reason, reason);
  1933. }
  1934. /** Called immediately before freeing a marked circuit <b>circ</b> from
  1935. * circuit_free_all() while shutting down Tor; this is a safe-at-shutdown
  1936. * version of circuit_about_to_free(). It's important that it at least
  1937. * do circuitmux_detach_circuit() when appropriate.
  1938. */
  1939. static void
  1940. circuit_about_to_free_atexit(circuit_t *circ)
  1941. {
  1942. if (circ->n_chan) {
  1943. circuit_clear_cell_queue(circ, circ->n_chan);
  1944. circuitmux_detach_circuit(circ->n_chan->cmux, circ);
  1945. circuit_set_n_circid_chan(circ, 0, NULL);
  1946. }
  1947. if (! CIRCUIT_IS_ORIGIN(circ)) {
  1948. or_circuit_t *or_circ = TO_OR_CIRCUIT(circ);
  1949. if (or_circ->p_chan) {
  1950. circuit_clear_cell_queue(circ, or_circ->p_chan);
  1951. circuitmux_detach_circuit(or_circ->p_chan->cmux, circ);
  1952. circuit_set_p_circid_chan(or_circ, 0, NULL);
  1953. }
  1954. }
  1955. }
  1956. /** Called immediately before freeing a marked circuit <b>circ</b>.
  1957. * Disconnects the circuit from other data structures, launches events
  1958. * as appropriate, and performs other housekeeping.
  1959. */
  1960. static void
  1961. circuit_about_to_free(circuit_t *circ)
  1962. {
  1963. int reason = circ->marked_for_close_reason;
  1964. int orig_reason = circ->marked_for_close_orig_reason;
  1965. if (circ->state == CIRCUIT_STATE_ONIONSKIN_PENDING) {
  1966. onion_pending_remove(TO_OR_CIRCUIT(circ));
  1967. }
  1968. /* If the circuit ever became OPEN, we sent it to the reputation history
  1969. * module then. If it isn't OPEN, we send it there now to remember which
  1970. * links worked and which didn't.
  1971. */
  1972. if (circ->state != CIRCUIT_STATE_OPEN &&
  1973. circ->state != CIRCUIT_STATE_GUARD_WAIT) {
  1974. if (CIRCUIT_IS_ORIGIN(circ)) {
  1975. origin_circuit_t *ocirc = TO_ORIGIN_CIRCUIT(circ);
  1976. circuit_build_failed(ocirc); /* take actions if necessary */
  1977. }
  1978. }
  1979. if (circ->state == CIRCUIT_STATE_CHAN_WAIT) {
  1980. if (circuits_pending_chans)
  1981. smartlist_remove(circuits_pending_chans, circ);
  1982. }
  1983. if (circuits_pending_other_guards) {
  1984. smartlist_remove(circuits_pending_other_guards, circ);
  1985. }
  1986. if (CIRCUIT_IS_ORIGIN(circ)) {
  1987. control_event_circuit_status(TO_ORIGIN_CIRCUIT(circ),
  1988. (circ->state == CIRCUIT_STATE_OPEN ||
  1989. circ->state == CIRCUIT_STATE_GUARD_WAIT) ?
  1990. CIRC_EVENT_CLOSED:CIRC_EVENT_FAILED,
  1991. orig_reason);
  1992. }
  1993. if (circ->purpose == CIRCUIT_PURPOSE_C_INTRODUCE_ACK_WAIT) {
  1994. origin_circuit_t *ocirc = TO_ORIGIN_CIRCUIT(circ);
  1995. int timed_out = (reason == END_CIRC_REASON_TIMEOUT);
  1996. tor_assert(circ->state == CIRCUIT_STATE_OPEN);
  1997. tor_assert(ocirc->build_state->chosen_exit);
  1998. if (orig_reason != END_CIRC_REASON_IP_NOW_REDUNDANT &&
  1999. ocirc->rend_data) {
  2000. /* treat this like getting a nack from it */
  2001. log_info(LD_REND, "Failed intro circ %s to %s (awaiting ack). %s",
  2002. safe_str_client(rend_data_get_address(ocirc->rend_data)),
  2003. safe_str_client(build_state_get_exit_nickname(ocirc->build_state)),
  2004. timed_out ? "Recording timeout." : "Removing from descriptor.");
  2005. rend_client_report_intro_point_failure(ocirc->build_state->chosen_exit,
  2006. ocirc->rend_data,
  2007. timed_out ?
  2008. INTRO_POINT_FAILURE_TIMEOUT :
  2009. INTRO_POINT_FAILURE_GENERIC);
  2010. }
  2011. } else if (circ->purpose == CIRCUIT_PURPOSE_C_INTRODUCING &&
  2012. reason != END_CIRC_REASON_TIMEOUT) {
  2013. origin_circuit_t *ocirc = TO_ORIGIN_CIRCUIT(circ);
  2014. if (ocirc->build_state->chosen_exit && ocirc->rend_data) {
  2015. if (orig_reason != END_CIRC_REASON_IP_NOW_REDUNDANT &&
  2016. ocirc->rend_data) {
  2017. log_info(LD_REND, "Failed intro circ %s to %s "
  2018. "(building circuit to intro point). "
  2019. "Marking intro point as possibly unreachable.",
  2020. safe_str_client(rend_data_get_address(ocirc->rend_data)),
  2021. safe_str_client(build_state_get_exit_nickname(
  2022. ocirc->build_state)));
  2023. rend_client_report_intro_point_failure(ocirc->build_state->chosen_exit,
  2024. ocirc->rend_data,
  2025. INTRO_POINT_FAILURE_UNREACHABLE);
  2026. }
  2027. }
  2028. }
  2029. if (circ->n_chan) {
  2030. circuit_clear_cell_queue(circ, circ->n_chan);
  2031. /* Only send destroy if the channel isn't closing anyway */
  2032. if (!CHANNEL_CONDEMNED(circ->n_chan)) {
  2033. channel_send_destroy(circ->n_circ_id, circ->n_chan, reason);
  2034. }
  2035. circuitmux_detach_circuit(circ->n_chan->cmux, circ);
  2036. circuit_set_n_circid_chan(circ, 0, NULL);
  2037. }
  2038. if (! CIRCUIT_IS_ORIGIN(circ)) {
  2039. or_circuit_t *or_circ = TO_OR_CIRCUIT(circ);
  2040. edge_connection_t *conn;
  2041. for (conn=or_circ->n_streams; conn; conn=conn->next_stream)
  2042. connection_edge_destroy(or_circ->p_circ_id, conn);
  2043. or_circ->n_streams = NULL;
  2044. while (or_circ->resolving_streams) {
  2045. conn = or_circ->resolving_streams;
  2046. or_circ->resolving_streams = conn->next_stream;
  2047. if (!conn->base_.marked_for_close) {
  2048. /* The client will see a DESTROY, and infer that the connections
  2049. * are closing because the circuit is getting torn down. No need
  2050. * to send an end cell. */
  2051. conn->edge_has_sent_end = 1;
  2052. conn->end_reason = END_STREAM_REASON_DESTROY;
  2053. conn->end_reason |= END_STREAM_REASON_FLAG_ALREADY_SENT_CLOSED;
  2054. connection_mark_for_close(TO_CONN(conn));
  2055. }
  2056. conn->on_circuit = NULL;
  2057. }
  2058. if (or_circ->p_chan) {
  2059. circuit_clear_cell_queue(circ, or_circ->p_chan);
  2060. /* Only send destroy if the channel isn't closing anyway */
  2061. if (!CHANNEL_CONDEMNED(or_circ->p_chan)) {
  2062. channel_send_destroy(or_circ->p_circ_id, or_circ->p_chan, reason);
  2063. }
  2064. circuitmux_detach_circuit(or_circ->p_chan->cmux, circ);
  2065. circuit_set_p_circid_chan(or_circ, 0, NULL);
  2066. }
  2067. } else {
  2068. origin_circuit_t *ocirc = TO_ORIGIN_CIRCUIT(circ);
  2069. edge_connection_t *conn;
  2070. for (conn=ocirc->p_streams; conn; conn=conn->next_stream)
  2071. connection_edge_destroy(circ->n_circ_id, conn);
  2072. ocirc->p_streams = NULL;
  2073. }
  2074. }
  2075. /** Given a marked circuit <b>circ</b>, aggressively free its cell queues to
  2076. * recover memory. */
  2077. static void
  2078. marked_circuit_free_cells(circuit_t *circ)
  2079. {
  2080. if (!circ->marked_for_close) {
  2081. log_warn(LD_BUG, "Called on non-marked circuit");
  2082. return;
  2083. }
  2084. cell_queue_clear(&circ->n_chan_cells);
  2085. if (circ->n_mux)
  2086. circuitmux_clear_num_cells(circ->n_mux, circ);
  2087. if (! CIRCUIT_IS_ORIGIN(circ)) {
  2088. or_circuit_t *orcirc = TO_OR_CIRCUIT(circ);
  2089. cell_queue_clear(&orcirc->p_chan_cells);
  2090. if (orcirc->p_mux)
  2091. circuitmux_clear_num_cells(orcirc->p_mux, circ);
  2092. }
  2093. }
  2094. static size_t
  2095. single_conn_free_bytes(connection_t *conn)
  2096. {
  2097. size_t result = 0;
  2098. if (conn->inbuf) {
  2099. result += buf_allocation(conn->inbuf);
  2100. buf_clear(conn->inbuf);
  2101. }
  2102. if (conn->outbuf) {
  2103. result += buf_allocation(conn->outbuf);
  2104. buf_clear(conn->outbuf);
  2105. conn->outbuf_flushlen = 0;
  2106. }
  2107. if (conn->type == CONN_TYPE_DIR) {
  2108. dir_connection_t *dir_conn = TO_DIR_CONN(conn);
  2109. if (dir_conn->compress_state) {
  2110. result += tor_compress_state_size(dir_conn->compress_state);
  2111. tor_compress_free(dir_conn->compress_state);
  2112. dir_conn->compress_state = NULL;
  2113. }
  2114. }
  2115. return result;
  2116. }
  2117. /** Aggressively free buffer contents on all the buffers of all streams in the
  2118. * list starting at <b>stream</b>. Return the number of bytes recovered. */
  2119. static size_t
  2120. marked_circuit_streams_free_bytes(edge_connection_t *stream)
  2121. {
  2122. size_t result = 0;
  2123. for ( ; stream; stream = stream->next_stream) {
  2124. connection_t *conn = TO_CONN(stream);
  2125. result += single_conn_free_bytes(conn);
  2126. if (conn->linked_conn) {
  2127. result += single_conn_free_bytes(conn->linked_conn);
  2128. }
  2129. }
  2130. return result;
  2131. }
  2132. /** Aggressively free buffer contents on all the buffers of all streams on
  2133. * circuit <b>c</b>. Return the number of bytes recovered. */
  2134. static size_t
  2135. marked_circuit_free_stream_bytes(circuit_t *c)
  2136. {
  2137. if (CIRCUIT_IS_ORIGIN(c)) {
  2138. return marked_circuit_streams_free_bytes(TO_ORIGIN_CIRCUIT(c)->p_streams);
  2139. } else {
  2140. return marked_circuit_streams_free_bytes(TO_OR_CIRCUIT(c)->n_streams);
  2141. }
  2142. }
  2143. /** Return the number of cells used by the circuit <b>c</b>'s cell queues. */
  2144. STATIC size_t
  2145. n_cells_in_circ_queues(const circuit_t *c)
  2146. {
  2147. size_t n = c->n_chan_cells.n;
  2148. if (! CIRCUIT_IS_ORIGIN(c)) {
  2149. circuit_t *cc = (circuit_t *) c;
  2150. n += TO_OR_CIRCUIT(cc)->p_chan_cells.n;
  2151. }
  2152. return n;
  2153. }
  2154. /** Return the number of bytes allocated for <b>c</b>'s half-open streams. */
  2155. static size_t
  2156. circuit_alloc_in_half_streams(const circuit_t *c)
  2157. {
  2158. if (! CIRCUIT_IS_ORIGIN(c)) {
  2159. return 0;
  2160. }
  2161. const origin_circuit_t *ocirc = CONST_TO_ORIGIN_CIRCUIT(c);
  2162. if (ocirc->half_streams)
  2163. return smartlist_len(ocirc->half_streams) * sizeof(half_edge_t);
  2164. else
  2165. return 0;
  2166. }
  2167. /**
  2168. * Return the age of the oldest cell queued on <b>c</b>, in timestamp units.
  2169. * Return 0 if there are no cells queued on c. Requires that <b>now</b> be
  2170. * the current coarse timestamp.
  2171. *
  2172. * This function will return incorrect results if the oldest cell queued on
  2173. * the circuit is older than about 2**32 msec (about 49 days) old.
  2174. */
  2175. STATIC uint32_t
  2176. circuit_max_queued_cell_age(const circuit_t *c, uint32_t now)
  2177. {
  2178. uint32_t age = 0;
  2179. packed_cell_t *cell;
  2180. if (NULL != (cell = TOR_SIMPLEQ_FIRST(&c->n_chan_cells.head)))
  2181. age = now - cell->inserted_timestamp;
  2182. if (! CIRCUIT_IS_ORIGIN(c)) {
  2183. const or_circuit_t *orcirc = CONST_TO_OR_CIRCUIT(c);
  2184. if (NULL != (cell = TOR_SIMPLEQ_FIRST(&orcirc->p_chan_cells.head))) {
  2185. uint32_t age2 = now - cell->inserted_timestamp;
  2186. if (age2 > age)
  2187. return age2;
  2188. }
  2189. }
  2190. return age;
  2191. }
  2192. /** Return the age of the oldest buffer chunk on <b>conn</b>, where age is
  2193. * taken in timestamp units before the time <b>now</b>. If the connection has
  2194. * no data, treat it as having age zero.
  2195. **/
  2196. static uint32_t
  2197. conn_get_buffer_age(const connection_t *conn, uint32_t now_ts)
  2198. {
  2199. uint32_t age = 0, age2;
  2200. if (conn->outbuf) {
  2201. age2 = buf_get_oldest_chunk_timestamp(conn->outbuf, now_ts);
  2202. if (age2 > age)
  2203. age = age2;
  2204. }
  2205. if (conn->inbuf) {
  2206. age2 = buf_get_oldest_chunk_timestamp(conn->inbuf, now_ts);
  2207. if (age2 > age)
  2208. age = age2;
  2209. }
  2210. return age;
  2211. }
  2212. /** Return the age in timestamp units of the oldest buffer chunk on any stream
  2213. * in the linked list <b>stream</b>, where age is taken in timestamp units
  2214. * before the timestamp <b>now</b>. */
  2215. static uint32_t
  2216. circuit_get_streams_max_data_age(const edge_connection_t *stream, uint32_t now)
  2217. {
  2218. uint32_t age = 0, age2;
  2219. for (; stream; stream = stream->next_stream) {
  2220. const connection_t *conn = TO_CONN(stream);
  2221. age2 = conn_get_buffer_age(conn, now);
  2222. if (age2 > age)
  2223. age = age2;
  2224. if (conn->linked_conn) {
  2225. age2 = conn_get_buffer_age(conn->linked_conn, now);
  2226. if (age2 > age)
  2227. age = age2;
  2228. }
  2229. }
  2230. return age;
  2231. }
  2232. /** Return the age in timestamp units of the oldest buffer chunk on any stream
  2233. * attached to the circuit <b>c</b>, where age is taken before the timestamp
  2234. * <b>now</b>. */
  2235. STATIC uint32_t
  2236. circuit_max_queued_data_age(const circuit_t *c, uint32_t now)
  2237. {
  2238. if (CIRCUIT_IS_ORIGIN(c)) {
  2239. return circuit_get_streams_max_data_age(
  2240. CONST_TO_ORIGIN_CIRCUIT(c)->p_streams, now);
  2241. } else {
  2242. return circuit_get_streams_max_data_age(
  2243. CONST_TO_OR_CIRCUIT(c)->n_streams, now);
  2244. }
  2245. }
  2246. /** Return the age of the oldest cell or stream buffer chunk on the circuit
  2247. * <b>c</b>, where age is taken in timestamp units before the timestamp
  2248. * <b>now</b> */
  2249. STATIC uint32_t
  2250. circuit_max_queued_item_age(const circuit_t *c, uint32_t now)
  2251. {
  2252. uint32_t cell_age = circuit_max_queued_cell_age(c, now);
  2253. uint32_t data_age = circuit_max_queued_data_age(c, now);
  2254. if (cell_age > data_age)
  2255. return cell_age;
  2256. else
  2257. return data_age;
  2258. }
  2259. /** Helper to sort a list of circuit_t by age of oldest item, in descending
  2260. * order. */
  2261. static int
  2262. circuits_compare_by_oldest_queued_item_(const void **a_, const void **b_)
  2263. {
  2264. const circuit_t *a = *a_;
  2265. const circuit_t *b = *b_;
  2266. uint32_t age_a = a->age_tmp;
  2267. uint32_t age_b = b->age_tmp;
  2268. if (age_a < age_b)
  2269. return 1;
  2270. else if (age_a == age_b)
  2271. return 0;
  2272. else
  2273. return -1;
  2274. }
  2275. static uint32_t now_ts_for_buf_cmp;
  2276. /** Helper to sort a list of circuit_t by age of oldest item, in descending
  2277. * order. */
  2278. static int
  2279. conns_compare_by_buffer_age_(const void **a_, const void **b_)
  2280. {
  2281. const connection_t *a = *a_;
  2282. const connection_t *b = *b_;
  2283. time_t age_a = conn_get_buffer_age(a, now_ts_for_buf_cmp);
  2284. time_t age_b = conn_get_buffer_age(b, now_ts_for_buf_cmp);
  2285. if (age_a < age_b)
  2286. return 1;
  2287. else if (age_a == age_b)
  2288. return 0;
  2289. else
  2290. return -1;
  2291. }
  2292. #define FRACTION_OF_DATA_TO_RETAIN_ON_OOM 0.90
  2293. /** We're out of memory for cells, having allocated <b>current_allocation</b>
  2294. * bytes' worth. Kill the 'worst' circuits until we're under
  2295. * FRACTION_OF_DATA_TO_RETAIN_ON_OOM of our maximum usage. */
  2296. void
  2297. circuits_handle_oom(size_t current_allocation)
  2298. {
  2299. smartlist_t *circlist;
  2300. smartlist_t *connection_array = get_connection_array();
  2301. int conn_idx;
  2302. size_t mem_to_recover;
  2303. size_t mem_recovered=0;
  2304. int n_circuits_killed=0;
  2305. int n_dirconns_killed=0;
  2306. uint32_t now_ts;
  2307. log_notice(LD_GENERAL, "We're low on memory (cell queues total alloc:"
  2308. " %"TOR_PRIuSZ" buffer total alloc: %" TOR_PRIuSZ ","
  2309. " tor compress total alloc: %" TOR_PRIuSZ
  2310. " (zlib: %" TOR_PRIuSZ ", zstd: %" TOR_PRIuSZ ","
  2311. " lzma: %" TOR_PRIuSZ "),"
  2312. " rendezvous cache total alloc: %" TOR_PRIuSZ "). Killing"
  2313. " circuits withover-long queues. (This behavior is controlled by"
  2314. " MaxMemInQueues.)",
  2315. cell_queues_get_total_allocation(),
  2316. buf_get_total_allocation(),
  2317. tor_compress_get_total_allocation(),
  2318. tor_zlib_get_total_allocation(),
  2319. tor_zstd_get_total_allocation(),
  2320. tor_lzma_get_total_allocation(),
  2321. rend_cache_get_total_allocation());
  2322. {
  2323. size_t mem_target = (size_t)(get_options()->MaxMemInQueues *
  2324. FRACTION_OF_DATA_TO_RETAIN_ON_OOM);
  2325. if (current_allocation <= mem_target)
  2326. return;
  2327. mem_to_recover = current_allocation - mem_target;
  2328. }
  2329. now_ts = monotime_coarse_get_stamp();
  2330. circlist = circuit_get_global_list();
  2331. SMARTLIST_FOREACH_BEGIN(circlist, circuit_t *, circ) {
  2332. circ->age_tmp = circuit_max_queued_item_age(circ, now_ts);
  2333. } SMARTLIST_FOREACH_END(circ);
  2334. /* This is O(n log n); there are faster algorithms we could use instead.
  2335. * Let's hope this doesn't happen enough to be in the critical path. */
  2336. smartlist_sort(circlist, circuits_compare_by_oldest_queued_item_);
  2337. /* Fix up the indices before we run into trouble */
  2338. SMARTLIST_FOREACH_BEGIN(circlist, circuit_t *, circ) {
  2339. circ->global_circuitlist_idx = circ_sl_idx;
  2340. } SMARTLIST_FOREACH_END(circ);
  2341. /* Now sort the connection array ... */
  2342. now_ts_for_buf_cmp = now_ts;
  2343. smartlist_sort(connection_array, conns_compare_by_buffer_age_);
  2344. now_ts_for_buf_cmp = 0;
  2345. /* Fix up the connection array to its new order. */
  2346. SMARTLIST_FOREACH_BEGIN(connection_array, connection_t *, conn) {
  2347. conn->conn_array_index = conn_sl_idx;
  2348. } SMARTLIST_FOREACH_END(conn);
  2349. /* Okay, now the worst circuits and connections are at the front of their
  2350. * respective lists. Let's mark them, and reclaim their storage
  2351. * aggressively. */
  2352. conn_idx = 0;
  2353. SMARTLIST_FOREACH_BEGIN(circlist, circuit_t *, circ) {
  2354. size_t n;
  2355. size_t freed;
  2356. /* Free storage in any non-linked directory connections that have buffered
  2357. * data older than this circuit. */
  2358. while (conn_idx < smartlist_len(connection_array)) {
  2359. connection_t *conn = smartlist_get(connection_array, conn_idx);
  2360. uint32_t conn_age = conn_get_buffer_age(conn, now_ts);
  2361. if (conn_age < circ->age_tmp) {
  2362. break;
  2363. }
  2364. if (conn->type == CONN_TYPE_DIR && conn->linked_conn == NULL) {
  2365. if (!conn->marked_for_close)
  2366. connection_mark_for_close(conn);
  2367. mem_recovered += single_conn_free_bytes(conn);
  2368. ++n_dirconns_killed;
  2369. if (mem_recovered >= mem_to_recover)
  2370. goto done_recovering_mem;
  2371. }
  2372. ++conn_idx;
  2373. }
  2374. /* Now, kill the circuit. */
  2375. n = n_cells_in_circ_queues(circ);
  2376. const size_t half_stream_alloc = circuit_alloc_in_half_streams(circ);
  2377. if (! circ->marked_for_close) {
  2378. circuit_mark_for_close(circ, END_CIRC_REASON_RESOURCELIMIT);
  2379. }
  2380. marked_circuit_free_cells(circ);
  2381. freed = marked_circuit_free_stream_bytes(circ);
  2382. ++n_circuits_killed;
  2383. mem_recovered += n * packed_cell_mem_cost();
  2384. mem_recovered += half_stream_alloc;
  2385. mem_recovered += freed;
  2386. if (mem_recovered >= mem_to_recover)
  2387. goto done_recovering_mem;
  2388. } SMARTLIST_FOREACH_END(circ);
  2389. done_recovering_mem:
  2390. log_notice(LD_GENERAL, "Removed %"TOR_PRIuSZ" bytes by killing %d circuits; "
  2391. "%d circuits remain alive. Also killed %d non-linked directory "
  2392. "connections.",
  2393. mem_recovered,
  2394. n_circuits_killed,
  2395. smartlist_len(circlist) - n_circuits_killed,
  2396. n_dirconns_killed);
  2397. }
  2398. /** Verify that cpath layer <b>cp</b> has all of its invariants
  2399. * correct. Trigger an assert if anything is invalid.
  2400. */
  2401. void
  2402. assert_cpath_layer_ok(const crypt_path_t *cp)
  2403. {
  2404. // tor_assert(cp->addr); /* these are zero for rendezvous extra-hops */
  2405. // tor_assert(cp->port);
  2406. tor_assert(cp);
  2407. tor_assert(cp->magic == CRYPT_PATH_MAGIC);
  2408. switch (cp->state)
  2409. {
  2410. case CPATH_STATE_OPEN:
  2411. relay_crypto_assert_ok(&cp->crypto);
  2412. /* fall through */
  2413. case CPATH_STATE_CLOSED:
  2414. /*XXXX Assert that there's no handshake_state either. */
  2415. tor_assert(!cp->rend_dh_handshake_state);
  2416. break;
  2417. case CPATH_STATE_AWAITING_KEYS:
  2418. /* tor_assert(cp->dh_handshake_state); */
  2419. break;
  2420. default:
  2421. log_fn(LOG_ERR, LD_BUG, "Unexpected state %d", cp->state);
  2422. tor_assert(0);
  2423. }
  2424. tor_assert(cp->package_window >= 0);
  2425. tor_assert(cp->deliver_window >= 0);
  2426. }
  2427. /** Verify that cpath <b>cp</b> has all of its invariants
  2428. * correct. Trigger an assert if anything is invalid.
  2429. */
  2430. static void
  2431. assert_cpath_ok(const crypt_path_t *cp)
  2432. {
  2433. const crypt_path_t *start = cp;
  2434. do {
  2435. assert_cpath_layer_ok(cp);
  2436. /* layers must be in sequence of: "open* awaiting? closed*" */
  2437. if (cp != start) {
  2438. if (cp->state == CPATH_STATE_AWAITING_KEYS) {
  2439. tor_assert(cp->prev->state == CPATH_STATE_OPEN);
  2440. } else if (cp->state == CPATH_STATE_OPEN) {
  2441. tor_assert(cp->prev->state == CPATH_STATE_OPEN);
  2442. }
  2443. }
  2444. cp = cp->next;
  2445. tor_assert(cp);
  2446. } while (cp != start);
  2447. }
  2448. /** Verify that circuit <b>c</b> has all of its invariants
  2449. * correct. Trigger an assert if anything is invalid.
  2450. */
  2451. MOCK_IMPL(void,
  2452. assert_circuit_ok,(const circuit_t *c))
  2453. {
  2454. edge_connection_t *conn;
  2455. const or_circuit_t *or_circ = NULL;
  2456. const origin_circuit_t *origin_circ = NULL;
  2457. tor_assert(c);
  2458. tor_assert(c->magic == ORIGIN_CIRCUIT_MAGIC || c->magic == OR_CIRCUIT_MAGIC);
  2459. tor_assert(c->purpose >= CIRCUIT_PURPOSE_MIN_ &&
  2460. c->purpose <= CIRCUIT_PURPOSE_MAX_);
  2461. if (CIRCUIT_IS_ORIGIN(c))
  2462. origin_circ = CONST_TO_ORIGIN_CIRCUIT(c);
  2463. else
  2464. or_circ = CONST_TO_OR_CIRCUIT(c);
  2465. if (c->n_chan) {
  2466. tor_assert(!c->n_hop);
  2467. if (c->n_circ_id) {
  2468. /* We use the _impl variant here to make sure we don't fail on marked
  2469. * circuits, which would not be returned by the regular function. */
  2470. circuit_t *c2 = circuit_get_by_circid_channel_impl(c->n_circ_id,
  2471. c->n_chan, NULL);
  2472. tor_assert(c == c2);
  2473. }
  2474. }
  2475. if (or_circ && or_circ->p_chan) {
  2476. if (or_circ->p_circ_id) {
  2477. /* ibid */
  2478. circuit_t *c2 =
  2479. circuit_get_by_circid_channel_impl(or_circ->p_circ_id,
  2480. or_circ->p_chan, NULL);
  2481. tor_assert(c == c2);
  2482. }
  2483. }
  2484. if (or_circ)
  2485. for (conn = or_circ->n_streams; conn; conn = conn->next_stream)
  2486. tor_assert(conn->base_.type == CONN_TYPE_EXIT);
  2487. tor_assert(c->deliver_window >= 0);
  2488. tor_assert(c->package_window >= 0);
  2489. if (c->state == CIRCUIT_STATE_OPEN ||
  2490. c->state == CIRCUIT_STATE_GUARD_WAIT) {
  2491. tor_assert(!c->n_chan_create_cell);
  2492. if (or_circ) {
  2493. relay_crypto_assert_ok(&or_circ->crypto);
  2494. }
  2495. }
  2496. if (c->state == CIRCUIT_STATE_CHAN_WAIT && !c->marked_for_close) {
  2497. tor_assert(circuits_pending_chans &&
  2498. smartlist_contains(circuits_pending_chans, c));
  2499. } else {
  2500. tor_assert(!circuits_pending_chans ||
  2501. !smartlist_contains(circuits_pending_chans, c));
  2502. }
  2503. if (origin_circ && origin_circ->cpath) {
  2504. assert_cpath_ok(origin_circ->cpath);
  2505. }
  2506. if (c->purpose == CIRCUIT_PURPOSE_REND_ESTABLISHED) {
  2507. tor_assert(or_circ);
  2508. if (!c->marked_for_close) {
  2509. tor_assert(or_circ->rend_splice);
  2510. tor_assert(or_circ->rend_splice->rend_splice == or_circ);
  2511. }
  2512. tor_assert(or_circ->rend_splice != or_circ);
  2513. } else {
  2514. tor_assert(!or_circ || !or_circ->rend_splice);
  2515. }
  2516. }