circuitlist.c 88 KB

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