circuitlist.c 78 KB

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