circuitlist.c 73 KB

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