circuitlist.c 91 KB

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