circuitlist.c 72 KB

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