circuitlist.c 92 KB

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