circuitlist.c 87 KB

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