circuitlist.c 90 KB

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