circuitlist.c 75 KB

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