circuitlist.c 94 KB

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