circuitlist.c 87 KB

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