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-2016, The Tor Project, Inc. */
  5. /* See LICENSE for licensing information */
  6. /**
  7. * \file circuitlist.c
  8. *
  9. * \brief Manage global structures that list and index circuits, and
  10. * look up circuits within them.
  11. *
  12. * One of the most frequent operations in Tor occurs every time that
  13. * a relay cell arrives on a channel. When that happens, we need to
  14. * find which circuit it is associated with, based on the channel and the
  15. * circuit ID in the relay cell.
  16. *
  17. * To handle that, we maintain a global list of circuits, and a hashtable
  18. * mapping [channel,circID] pairs to circuits. Circuits are added to and
  19. * removed from this mapping using circuit_set_p_circid_chan() and
  20. * circuit_set_n_circid_chan(). To look up a circuit from this map, most
  21. * callers should use circuit_get_by_circid_channel(), though
  22. * circuit_get_by_circid_channel_even_if_marked() is appropriate under some
  23. * circumstances.
  24. *
  25. * We also need to allow for the possibility that we have blocked use of a
  26. * circuit ID (because we are waiting to send a DESTROY cell), but the
  27. * circuit is not there any more. For that case, we allow placeholder
  28. * entries in the table, using channel_mark_circid_unusable().
  29. *
  30. * To efficiently handle a channel that has just opened, we also maintain a
  31. * list of the circuits waiting for channels, so we can attach them as
  32. * needed without iterating through the whole list of circuits, using
  33. * circuit_get_all_pending_on_channel().
  34. *
  35. * In this module, we also handle the list of circuits that have been
  36. * marked for close elsewhere, and close them as needed. (We use this
  37. * "mark now, close later" pattern here and elsewhere to avoid
  38. * unpredictable recursion if we closed every circuit immediately upon
  39. * realizing it needed to close.) See circuit_mark_for_close() for the
  40. * mark function, and circuit_close_all_marked() for the close function.
  41. *
  42. * For hidden services, we need to be able to look up introduction point
  43. * circuits and rendezvous circuits by cookie, key, etc. These are
  44. * currently handled with linear searches in
  45. * circuit_get_ready_rend_circuit_by_rend_data(),
  46. * circuit_get_next_by_pk_and_purpose(), and with hash lookups in
  47. * circuit_get_rendezvous() and circuit_get_intro_point().
  48. *
  49. * This module is also the entry point for our out-of-memory handler
  50. * logic, which was originally circuit-focused.
  51. **/
  52. #define CIRCUITLIST_PRIVATE
  53. #include "or.h"
  54. #include "channel.h"
  55. #include "circpathbias.h"
  56. #include "circuitbuild.h"
  57. #include "circuitlist.h"
  58. #include "circuituse.h"
  59. #include "circuitstats.h"
  60. #include "connection.h"
  61. #include "config.h"
  62. #include "connection_edge.h"
  63. #include "connection_or.h"
  64. #include "control.h"
  65. #include "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->hs_token) {
  833. hs_circuitmap_remove_circuit(ocirc);
  834. }
  835. if (ocirc->rend_splice) {
  836. or_circuit_t *other = ocirc->rend_splice;
  837. tor_assert(other->base_.magic == OR_CIRCUIT_MAGIC);
  838. other->rend_splice = NULL;
  839. }
  840. /* remove from map. */
  841. circuit_set_p_circid_chan(ocirc, 0, NULL);
  842. /* Clear cell queue _after_ removing it from the map. Otherwise our
  843. * "active" checks will be violated. */
  844. cell_queue_clear(&ocirc->p_chan_cells);
  845. }
  846. extend_info_free(circ->n_hop);
  847. tor_free(circ->n_chan_create_cell);
  848. if (circ->global_circuitlist_idx != -1) {
  849. int idx = circ->global_circuitlist_idx;
  850. circuit_t *c2 = smartlist_get(global_circuitlist, idx);
  851. tor_assert(c2 == circ);
  852. smartlist_del(global_circuitlist, idx);
  853. if (idx < smartlist_len(global_circuitlist)) {
  854. c2 = smartlist_get(global_circuitlist, idx);
  855. c2->global_circuitlist_idx = idx;
  856. }
  857. }
  858. /* Remove from map. */
  859. circuit_set_n_circid_chan(circ, 0, NULL);
  860. /* Clear cell queue _after_ removing it from the map. Otherwise our
  861. * "active" checks will be violated. */
  862. cell_queue_clear(&circ->n_chan_cells);
  863. if (should_free) {
  864. memwipe(mem, 0xAA, memlen); /* poison memory */
  865. tor_free(mem);
  866. } else {
  867. /* If we made it here, this is an or_circuit_t that still has a pending
  868. * cpuworker request which we weren't able to cancel. Instead, set up
  869. * the magic value so that when the reply comes back, we'll know to discard
  870. * the reply and free this structure.
  871. */
  872. memwipe(mem, 0xAA, memlen);
  873. circ->magic = DEAD_CIRCUIT_MAGIC;
  874. }
  875. }
  876. /** Deallocate the linked list circ-><b>cpath</b>, and remove the cpath from
  877. * <b>circ</b>. */
  878. void
  879. circuit_clear_cpath(origin_circuit_t *circ)
  880. {
  881. crypt_path_t *victim, *head, *cpath;
  882. head = cpath = circ->cpath;
  883. if (!cpath)
  884. return;
  885. /* it's a circular list, so we have to notice when we've
  886. * gone through it once. */
  887. while (cpath->next && cpath->next != head) {
  888. victim = cpath;
  889. cpath = victim->next;
  890. circuit_free_cpath_node(victim);
  891. }
  892. circuit_free_cpath_node(cpath);
  893. circ->cpath = NULL;
  894. }
  895. /** Release all storage held by circuits. */
  896. void
  897. circuit_free_all(void)
  898. {
  899. smartlist_t *lst = circuit_get_global_list();
  900. SMARTLIST_FOREACH_BEGIN(lst, circuit_t *, tmp) {
  901. if (! CIRCUIT_IS_ORIGIN(tmp)) {
  902. or_circuit_t *or_circ = TO_OR_CIRCUIT(tmp);
  903. while (or_circ->resolving_streams) {
  904. edge_connection_t *next_conn;
  905. next_conn = or_circ->resolving_streams->next_stream;
  906. connection_free(TO_CONN(or_circ->resolving_streams));
  907. or_circ->resolving_streams = next_conn;
  908. }
  909. }
  910. tmp->global_circuitlist_idx = -1;
  911. circuit_about_to_free_atexit(tmp);
  912. circuit_free(tmp);
  913. SMARTLIST_DEL_CURRENT(lst, tmp);
  914. } SMARTLIST_FOREACH_END(tmp);
  915. smartlist_free(lst);
  916. global_circuitlist = NULL;
  917. smartlist_free(global_origin_circuit_list);
  918. global_origin_circuit_list = NULL;
  919. smartlist_free(circuits_pending_chans);
  920. circuits_pending_chans = NULL;
  921. smartlist_free(circuits_pending_close);
  922. circuits_pending_close = NULL;
  923. smartlist_free(circuits_pending_other_guards);
  924. circuits_pending_other_guards = NULL;
  925. {
  926. chan_circid_circuit_map_t **elt, **next, *c;
  927. for (elt = HT_START(chan_circid_map, &chan_circid_map);
  928. elt;
  929. elt = next) {
  930. c = *elt;
  931. next = HT_NEXT_RMV(chan_circid_map, &chan_circid_map, elt);
  932. tor_assert(c->circuit == NULL);
  933. tor_free(c);
  934. }
  935. }
  936. HT_CLEAR(chan_circid_map, &chan_circid_map);
  937. }
  938. /** Deallocate space associated with the cpath node <b>victim</b>. */
  939. static void
  940. circuit_free_cpath_node(crypt_path_t *victim)
  941. {
  942. if (!victim)
  943. return;
  944. crypto_cipher_free(victim->f_crypto);
  945. crypto_cipher_free(victim->b_crypto);
  946. crypto_digest_free(victim->f_digest);
  947. crypto_digest_free(victim->b_digest);
  948. onion_handshake_state_release(&victim->handshake_state);
  949. crypto_dh_free(victim->rend_dh_handshake_state);
  950. extend_info_free(victim->extend_info);
  951. memwipe(victim, 0xBB, sizeof(crypt_path_t)); /* poison memory */
  952. tor_free(victim);
  953. }
  954. /** Release a crypt_path_reference_t*, which may be NULL. */
  955. static void
  956. cpath_ref_decref(crypt_path_reference_t *cpath_ref)
  957. {
  958. if (cpath_ref != NULL) {
  959. if (--(cpath_ref->refcount) == 0) {
  960. circuit_free_cpath_node(cpath_ref->cpath);
  961. tor_free(cpath_ref);
  962. }
  963. }
  964. }
  965. /** A helper function for circuit_dump_by_conn() below. Log a bunch
  966. * of information about circuit <b>circ</b>.
  967. */
  968. static void
  969. circuit_dump_conn_details(int severity,
  970. circuit_t *circ,
  971. int conn_array_index,
  972. const char *type,
  973. circid_t this_circid,
  974. circid_t other_circid)
  975. {
  976. tor_log(severity, LD_CIRC, "Conn %d has %s circuit: circID %u "
  977. "(other side %u), state %d (%s), born %ld:",
  978. conn_array_index, type, (unsigned)this_circid, (unsigned)other_circid,
  979. circ->state, circuit_state_to_string(circ->state),
  980. (long)circ->timestamp_began.tv_sec);
  981. if (CIRCUIT_IS_ORIGIN(circ)) { /* circ starts at this node */
  982. circuit_log_path(severity, LD_CIRC, TO_ORIGIN_CIRCUIT(circ));
  983. }
  984. }
  985. /** Log, at severity <b>severity</b>, information about each circuit
  986. * that is connected to <b>conn</b>.
  987. */
  988. void
  989. circuit_dump_by_conn(connection_t *conn, int severity)
  990. {
  991. edge_connection_t *tmpconn;
  992. SMARTLIST_FOREACH_BEGIN(circuit_get_global_list(), circuit_t *, circ) {
  993. circid_t n_circ_id = circ->n_circ_id, p_circ_id = 0;
  994. if (circ->marked_for_close) {
  995. continue;
  996. }
  997. if (!CIRCUIT_IS_ORIGIN(circ)) {
  998. p_circ_id = TO_OR_CIRCUIT(circ)->p_circ_id;
  999. }
  1000. if (CIRCUIT_IS_ORIGIN(circ)) {
  1001. for (tmpconn=TO_ORIGIN_CIRCUIT(circ)->p_streams; tmpconn;
  1002. tmpconn=tmpconn->next_stream) {
  1003. if (TO_CONN(tmpconn) == conn) {
  1004. circuit_dump_conn_details(severity, circ, conn->conn_array_index,
  1005. "App-ward", p_circ_id, n_circ_id);
  1006. }
  1007. }
  1008. }
  1009. if (! CIRCUIT_IS_ORIGIN(circ)) {
  1010. for (tmpconn=TO_OR_CIRCUIT(circ)->n_streams; tmpconn;
  1011. tmpconn=tmpconn->next_stream) {
  1012. if (TO_CONN(tmpconn) == conn) {
  1013. circuit_dump_conn_details(severity, circ, conn->conn_array_index,
  1014. "Exit-ward", n_circ_id, p_circ_id);
  1015. }
  1016. }
  1017. }
  1018. }
  1019. SMARTLIST_FOREACH_END(circ);
  1020. }
  1021. /** Return the circuit whose global ID is <b>id</b>, or NULL if no
  1022. * such circuit exists. */
  1023. origin_circuit_t *
  1024. circuit_get_by_global_id(uint32_t id)
  1025. {
  1026. SMARTLIST_FOREACH_BEGIN(circuit_get_global_list(), circuit_t *, circ) {
  1027. if (CIRCUIT_IS_ORIGIN(circ) &&
  1028. TO_ORIGIN_CIRCUIT(circ)->global_identifier == id) {
  1029. if (circ->marked_for_close)
  1030. return NULL;
  1031. else
  1032. return TO_ORIGIN_CIRCUIT(circ);
  1033. }
  1034. }
  1035. SMARTLIST_FOREACH_END(circ);
  1036. return NULL;
  1037. }
  1038. /** Return a circ such that:
  1039. * - circ-\>n_circ_id or circ-\>p_circ_id is equal to <b>circ_id</b>, and
  1040. * - circ is attached to <b>chan</b>, either as p_chan or n_chan.
  1041. * Return NULL if no such circuit exists.
  1042. *
  1043. * If <b>found_entry_out</b> is provided, set it to true if we have a
  1044. * placeholder entry for circid/chan, and leave it unset otherwise.
  1045. */
  1046. static inline circuit_t *
  1047. circuit_get_by_circid_channel_impl(circid_t circ_id, channel_t *chan,
  1048. int *found_entry_out)
  1049. {
  1050. chan_circid_circuit_map_t search;
  1051. chan_circid_circuit_map_t *found;
  1052. if (_last_circid_chan_ent &&
  1053. circ_id == _last_circid_chan_ent->circ_id &&
  1054. chan == _last_circid_chan_ent->chan) {
  1055. found = _last_circid_chan_ent;
  1056. } else {
  1057. search.circ_id = circ_id;
  1058. search.chan = chan;
  1059. found = HT_FIND(chan_circid_map, &chan_circid_map, &search);
  1060. _last_circid_chan_ent = found;
  1061. }
  1062. if (found && found->circuit) {
  1063. log_debug(LD_CIRC,
  1064. "circuit_get_by_circid_channel_impl() returning circuit %p for"
  1065. " circ_id %u, channel ID " U64_FORMAT " (%p)",
  1066. found->circuit, (unsigned)circ_id,
  1067. U64_PRINTF_ARG(chan->global_identifier), chan);
  1068. if (found_entry_out)
  1069. *found_entry_out = 1;
  1070. return found->circuit;
  1071. }
  1072. log_debug(LD_CIRC,
  1073. "circuit_get_by_circid_channel_impl() found %s for"
  1074. " circ_id %u, channel ID " U64_FORMAT " (%p)",
  1075. found ? "placeholder" : "nothing",
  1076. (unsigned)circ_id,
  1077. U64_PRINTF_ARG(chan->global_identifier), chan);
  1078. if (found_entry_out)
  1079. *found_entry_out = found ? 1 : 0;
  1080. return NULL;
  1081. /* The rest of this checks for bugs. Disabled by default. */
  1082. /* We comment it out because coverity complains otherwise.
  1083. {
  1084. circuit_t *circ;
  1085. TOR_LIST_FOREACH(circ, &global_circuitlist, head) {
  1086. if (! CIRCUIT_IS_ORIGIN(circ)) {
  1087. or_circuit_t *or_circ = TO_OR_CIRCUIT(circ);
  1088. if (or_circ->p_chan == chan && or_circ->p_circ_id == circ_id) {
  1089. log_warn(LD_BUG,
  1090. "circuit matches p_chan, but not in hash table (Bug!)");
  1091. return circ;
  1092. }
  1093. }
  1094. if (circ->n_chan == chan && circ->n_circ_id == circ_id) {
  1095. log_warn(LD_BUG,
  1096. "circuit matches n_chan, but not in hash table (Bug!)");
  1097. return circ;
  1098. }
  1099. }
  1100. return NULL;
  1101. } */
  1102. }
  1103. /** Return a circ such that:
  1104. * - circ-\>n_circ_id or circ-\>p_circ_id is equal to <b>circ_id</b>, and
  1105. * - circ is attached to <b>chan</b>, either as p_chan or n_chan.
  1106. * - circ is not marked for close.
  1107. * Return NULL if no such circuit exists.
  1108. */
  1109. circuit_t *
  1110. circuit_get_by_circid_channel(circid_t circ_id, channel_t *chan)
  1111. {
  1112. circuit_t *circ = circuit_get_by_circid_channel_impl(circ_id, chan, NULL);
  1113. if (!circ || circ->marked_for_close)
  1114. return NULL;
  1115. else
  1116. return circ;
  1117. }
  1118. /** Return a circ such that:
  1119. * - circ-\>n_circ_id or circ-\>p_circ_id is equal to <b>circ_id</b>, and
  1120. * - circ is attached to <b>chan</b>, either as p_chan or n_chan.
  1121. * Return NULL if no such circuit exists.
  1122. */
  1123. circuit_t *
  1124. circuit_get_by_circid_channel_even_if_marked(circid_t circ_id,
  1125. channel_t *chan)
  1126. {
  1127. return circuit_get_by_circid_channel_impl(circ_id, chan, NULL);
  1128. }
  1129. /** Return true iff the circuit ID <b>circ_id</b> is currently used by a
  1130. * circuit, marked or not, on <b>chan</b>, or if the circ ID is reserved until
  1131. * a queued destroy cell can be sent.
  1132. *
  1133. * (Return 1 if the circuit is present, marked or not; Return 2
  1134. * if the circuit ID is pending a destroy.)
  1135. **/
  1136. int
  1137. circuit_id_in_use_on_channel(circid_t circ_id, channel_t *chan)
  1138. {
  1139. int found = 0;
  1140. if (circuit_get_by_circid_channel_impl(circ_id, chan, &found) != NULL)
  1141. return 1;
  1142. if (found)
  1143. return 2;
  1144. return 0;
  1145. }
  1146. /** Helper for debugging 12184. Returns the time since which 'circ_id' has
  1147. * been marked unusable on 'chan'. */
  1148. time_t
  1149. circuit_id_when_marked_unusable_on_channel(circid_t circ_id, channel_t *chan)
  1150. {
  1151. chan_circid_circuit_map_t search;
  1152. chan_circid_circuit_map_t *found;
  1153. memset(&search, 0, sizeof(search));
  1154. search.circ_id = circ_id;
  1155. search.chan = chan;
  1156. found = HT_FIND(chan_circid_map, &chan_circid_map, &search);
  1157. if (! found || found->circuit)
  1158. return 0;
  1159. return found->made_placeholder_at;
  1160. }
  1161. /** Return the circuit that a given edge connection is using. */
  1162. circuit_t *
  1163. circuit_get_by_edge_conn(edge_connection_t *conn)
  1164. {
  1165. circuit_t *circ;
  1166. circ = conn->on_circuit;
  1167. tor_assert(!circ ||
  1168. (CIRCUIT_IS_ORIGIN(circ) ? circ->magic == ORIGIN_CIRCUIT_MAGIC
  1169. : circ->magic == OR_CIRCUIT_MAGIC));
  1170. return circ;
  1171. }
  1172. /** For each circuit that has <b>chan</b> as n_chan or p_chan, unlink the
  1173. * circuit from the chan,circid map, and mark it for close if it hasn't
  1174. * been marked already.
  1175. */
  1176. void
  1177. circuit_unlink_all_from_channel(channel_t *chan, int reason)
  1178. {
  1179. smartlist_t *detached = smartlist_new();
  1180. /* #define DEBUG_CIRCUIT_UNLINK_ALL */
  1181. channel_unlink_all_circuits(chan, detached);
  1182. #ifdef DEBUG_CIRCUIT_UNLINK_ALL
  1183. {
  1184. smartlist_t *detached_2 = smartlist_new();
  1185. int mismatch = 0, badlen = 0;
  1186. SMARTLIST_FOREACH_BEGIN(circuit_get_global_list(), circuit_t *, circ) {
  1187. if (circ->n_chan == chan ||
  1188. (!CIRCUIT_IS_ORIGIN(circ) &&
  1189. TO_OR_CIRCUIT(circ)->p_chan == chan)) {
  1190. smartlist_add(detached_2, circ);
  1191. }
  1192. }
  1193. SMARTLIST_FOREACH_END(circ);
  1194. if (smartlist_len(detached) != smartlist_len(detached_2)) {
  1195. log_warn(LD_BUG, "List of detached circuits had the wrong length! "
  1196. "(got %d, should have gotten %d)",
  1197. (int)smartlist_len(detached),
  1198. (int)smartlist_len(detached_2));
  1199. badlen = 1;
  1200. }
  1201. smartlist_sort_pointers(detached);
  1202. smartlist_sort_pointers(detached_2);
  1203. SMARTLIST_FOREACH(detached, circuit_t *, c,
  1204. if (c != smartlist_get(detached_2, c_sl_idx))
  1205. mismatch = 1;
  1206. );
  1207. if (mismatch)
  1208. log_warn(LD_BUG, "Mismatch in list of detached circuits.");
  1209. if (badlen || mismatch) {
  1210. smartlist_free(detached);
  1211. detached = detached_2;
  1212. } else {
  1213. log_notice(LD_CIRC, "List of %d circuits was as expected.",
  1214. (int)smartlist_len(detached));
  1215. smartlist_free(detached_2);
  1216. }
  1217. }
  1218. #endif
  1219. SMARTLIST_FOREACH_BEGIN(detached, circuit_t *, circ) {
  1220. int mark = 0;
  1221. if (circ->n_chan == chan) {
  1222. circuit_set_n_circid_chan(circ, 0, NULL);
  1223. mark = 1;
  1224. /* If we didn't request this closure, pass the remote
  1225. * bit to mark_for_close. */
  1226. if (chan->reason_for_closing != CHANNEL_CLOSE_REQUESTED)
  1227. reason |= END_CIRC_REASON_FLAG_REMOTE;
  1228. }
  1229. if (! CIRCUIT_IS_ORIGIN(circ)) {
  1230. or_circuit_t *or_circ = TO_OR_CIRCUIT(circ);
  1231. if (or_circ->p_chan == chan) {
  1232. circuit_set_p_circid_chan(or_circ, 0, NULL);
  1233. mark = 1;
  1234. }
  1235. }
  1236. if (!mark) {
  1237. log_warn(LD_BUG, "Circuit on detached list which I had no reason "
  1238. "to mark");
  1239. continue;
  1240. }
  1241. if (!circ->marked_for_close)
  1242. circuit_mark_for_close(circ, reason);
  1243. } SMARTLIST_FOREACH_END(circ);
  1244. smartlist_free(detached);
  1245. }
  1246. /** Return a circ such that
  1247. * - circ-\>rend_data-\>onion_address is equal to
  1248. * <b>rend_data</b>-\>onion_address,
  1249. * - circ-\>rend_data-\>rend_cookie is equal to
  1250. * <b>rend_data</b>-\>rend_cookie, and
  1251. * - circ-\>purpose is equal to CIRCUIT_PURPOSE_C_REND_READY.
  1252. *
  1253. * Return NULL if no such circuit exists.
  1254. */
  1255. origin_circuit_t *
  1256. circuit_get_ready_rend_circ_by_rend_data(const rend_data_t *rend_data)
  1257. {
  1258. SMARTLIST_FOREACH_BEGIN(circuit_get_global_list(), circuit_t *, circ) {
  1259. if (!circ->marked_for_close &&
  1260. circ->purpose == CIRCUIT_PURPOSE_C_REND_READY) {
  1261. origin_circuit_t *ocirc = TO_ORIGIN_CIRCUIT(circ);
  1262. if (ocirc->rend_data == NULL) {
  1263. continue;
  1264. }
  1265. if (!rend_cmp_service_ids(rend_data_get_address(rend_data),
  1266. rend_data_get_address(ocirc->rend_data)) &&
  1267. tor_memeq(ocirc->rend_data->rend_cookie,
  1268. rend_data->rend_cookie,
  1269. REND_COOKIE_LEN))
  1270. return ocirc;
  1271. }
  1272. }
  1273. SMARTLIST_FOREACH_END(circ);
  1274. return NULL;
  1275. }
  1276. /** Return the first service introduction circuit originating from the global
  1277. * circuit list after <b>start</b> or at the start of the list if <b>start</b>
  1278. * is NULL. Return NULL if no circuit is found.
  1279. *
  1280. * A service introduction point circuit has a purpose of either
  1281. * CIRCUIT_PURPOSE_S_ESTABLISH_INTRO or CIRCUIT_PURPOSE_S_INTRO. This does not
  1282. * return a circuit marked for close and its state must be open. */
  1283. origin_circuit_t *
  1284. circuit_get_next_service_intro_circ(origin_circuit_t *start)
  1285. {
  1286. int idx = 0;
  1287. smartlist_t *lst = circuit_get_global_list();
  1288. if (start) {
  1289. idx = TO_CIRCUIT(start)->global_circuitlist_idx + 1;
  1290. }
  1291. for ( ; idx < smartlist_len(lst); ++idx) {
  1292. circuit_t *circ = smartlist_get(lst, idx);
  1293. /* Ignore a marked for close circuit or purpose not matching a service
  1294. * intro point or if the state is not open. */
  1295. if (circ->marked_for_close || circ->state != CIRCUIT_STATE_OPEN ||
  1296. (circ->purpose != CIRCUIT_PURPOSE_S_ESTABLISH_INTRO &&
  1297. circ->purpose != CIRCUIT_PURPOSE_S_INTRO)) {
  1298. continue;
  1299. }
  1300. /* The purposes we are looking for are only for origin circuits so the
  1301. * following is valid. */
  1302. return TO_ORIGIN_CIRCUIT(circ);
  1303. }
  1304. /* Not found. */
  1305. return NULL;
  1306. }
  1307. /** Return the first circuit originating here in global_circuitlist after
  1308. * <b>start</b> whose purpose is <b>purpose</b>, and where <b>digest</b> (if
  1309. * set) matches the private key digest of the rend data associated with the
  1310. * circuit. Return NULL if no circuit is found. If <b>start</b> is NULL,
  1311. * begin at the start of the list.
  1312. */
  1313. origin_circuit_t *
  1314. circuit_get_next_by_pk_and_purpose(origin_circuit_t *start,
  1315. const uint8_t *digest, uint8_t purpose)
  1316. {
  1317. int idx;
  1318. smartlist_t *lst = circuit_get_global_list();
  1319. tor_assert(CIRCUIT_PURPOSE_IS_ORIGIN(purpose));
  1320. if (start == NULL)
  1321. idx = 0;
  1322. else
  1323. idx = TO_CIRCUIT(start)->global_circuitlist_idx + 1;
  1324. for ( ; idx < smartlist_len(lst); ++idx) {
  1325. circuit_t *circ = smartlist_get(lst, idx);
  1326. origin_circuit_t *ocirc;
  1327. if (circ->marked_for_close)
  1328. continue;
  1329. if (circ->purpose != purpose)
  1330. continue;
  1331. /* At this point we should be able to get a valid origin circuit because
  1332. * the origin purpose we are looking for matches this circuit. */
  1333. if (BUG(!CIRCUIT_PURPOSE_IS_ORIGIN(circ->purpose))) {
  1334. break;
  1335. }
  1336. ocirc = TO_ORIGIN_CIRCUIT(circ);
  1337. if (!digest)
  1338. return ocirc;
  1339. if (rend_circuit_pk_digest_eq(ocirc, digest)) {
  1340. return ocirc;
  1341. }
  1342. }
  1343. return NULL;
  1344. }
  1345. /** Return a circuit that is open, is CIRCUIT_PURPOSE_C_GENERAL,
  1346. * has a timestamp_dirty value of 0, has flags matching the CIRCLAUNCH_*
  1347. * flags in <b>flags</b>, and if info is defined, does not already use info
  1348. * as any of its hops; or NULL if no circuit fits this description.
  1349. *
  1350. * The <b>purpose</b> argument (currently ignored) refers to the purpose of
  1351. * the circuit we want to create, not the purpose of the circuit we want to
  1352. * cannibalize.
  1353. *
  1354. * If !CIRCLAUNCH_NEED_UPTIME, prefer returning non-uptime circuits.
  1355. *
  1356. * To "cannibalize" a circuit means to extend it an extra hop, and use it
  1357. * for some other purpose than we had originally intended. We do this when
  1358. * we want to perform some low-bandwidth task at a specific relay, and we
  1359. * would like the circuit to complete as soon as possible. (If we were going
  1360. * to use a lot of bandwidth, we wouldn't want a circuit with an extra hop.
  1361. * If we didn't care about circuit completion latency, we would just build
  1362. * a new circuit.)
  1363. */
  1364. origin_circuit_t *
  1365. circuit_find_to_cannibalize(uint8_t purpose, extend_info_t *info,
  1366. int flags)
  1367. {
  1368. origin_circuit_t *best=NULL;
  1369. int need_uptime = (flags & CIRCLAUNCH_NEED_UPTIME) != 0;
  1370. int need_capacity = (flags & CIRCLAUNCH_NEED_CAPACITY) != 0;
  1371. int internal = (flags & CIRCLAUNCH_IS_INTERNAL) != 0;
  1372. const or_options_t *options = get_options();
  1373. /* Make sure we're not trying to create a onehop circ by
  1374. * cannibalization. */
  1375. tor_assert(!(flags & CIRCLAUNCH_ONEHOP_TUNNEL));
  1376. log_debug(LD_CIRC,
  1377. "Hunting for a circ to cannibalize: purpose %d, uptime %d, "
  1378. "capacity %d, internal %d",
  1379. purpose, need_uptime, need_capacity, internal);
  1380. SMARTLIST_FOREACH_BEGIN(circuit_get_global_list(), circuit_t *, circ_) {
  1381. if (CIRCUIT_IS_ORIGIN(circ_) &&
  1382. circ_->state == CIRCUIT_STATE_OPEN &&
  1383. !circ_->marked_for_close &&
  1384. circ_->purpose == CIRCUIT_PURPOSE_C_GENERAL &&
  1385. !circ_->timestamp_dirty) {
  1386. origin_circuit_t *circ = TO_ORIGIN_CIRCUIT(circ_);
  1387. if ((!need_uptime || circ->build_state->need_uptime) &&
  1388. (!need_capacity || circ->build_state->need_capacity) &&
  1389. (internal == circ->build_state->is_internal) &&
  1390. !circ->unusable_for_new_conns &&
  1391. circ->remaining_relay_early_cells &&
  1392. circ->build_state->desired_path_len == DEFAULT_ROUTE_LEN &&
  1393. !circ->build_state->onehop_tunnel &&
  1394. !circ->isolation_values_set) {
  1395. if (info) {
  1396. /* need to make sure we don't duplicate hops */
  1397. crypt_path_t *hop = circ->cpath;
  1398. const node_t *ri1 = node_get_by_id(info->identity_digest);
  1399. do {
  1400. const node_t *ri2;
  1401. if (tor_memeq(hop->extend_info->identity_digest,
  1402. info->identity_digest, DIGEST_LEN))
  1403. goto next;
  1404. if (ri1 &&
  1405. (ri2 = node_get_by_id(hop->extend_info->identity_digest))
  1406. && nodes_in_same_family(ri1, ri2))
  1407. goto next;
  1408. hop=hop->next;
  1409. } while (hop!=circ->cpath);
  1410. }
  1411. if (options->ExcludeNodes) {
  1412. /* Make sure no existing nodes in the circuit are excluded for
  1413. * general use. (This may be possible if StrictNodes is 0, and we
  1414. * thought we needed to use an otherwise excluded node for, say, a
  1415. * directory operation.) */
  1416. crypt_path_t *hop = circ->cpath;
  1417. do {
  1418. if (routerset_contains_extendinfo(options->ExcludeNodes,
  1419. hop->extend_info))
  1420. goto next;
  1421. hop = hop->next;
  1422. } while (hop != circ->cpath);
  1423. }
  1424. if (!best || (best->build_state->need_uptime && !need_uptime))
  1425. best = circ;
  1426. next: ;
  1427. }
  1428. }
  1429. }
  1430. SMARTLIST_FOREACH_END(circ_);
  1431. return best;
  1432. }
  1433. /**
  1434. * Check whether any of the origin circuits that are waiting to see if
  1435. * their guard is good enough to use can be upgraded to "ready". If so,
  1436. * return a new smartlist containing them. Otherwise return NULL.
  1437. */
  1438. smartlist_t *
  1439. circuit_find_circuits_to_upgrade_from_guard_wait(void)
  1440. {
  1441. /* Only if some circuit is actually waiting on an upgrade should we
  1442. * run the algorithm. */
  1443. if (! circuits_pending_other_guards ||
  1444. smartlist_len(circuits_pending_other_guards)==0)
  1445. return NULL;
  1446. /* Only if we have some origin circuits should we run the algorithm. */
  1447. if (!global_origin_circuit_list)
  1448. return NULL;
  1449. /* Okay; we can pass our circuit list to entrynodes.c.*/
  1450. smartlist_t *result = smartlist_new();
  1451. int circuits_upgraded = entry_guards_upgrade_waiting_circuits(
  1452. get_guard_selection_info(),
  1453. global_origin_circuit_list,
  1454. result);
  1455. if (circuits_upgraded && smartlist_len(result)) {
  1456. return result;
  1457. } else {
  1458. smartlist_free(result);
  1459. return NULL;
  1460. }
  1461. }
  1462. /** Return the number of hops in circuit's path. If circ has no entries,
  1463. * or is NULL, returns 0. */
  1464. int
  1465. circuit_get_cpath_len(origin_circuit_t *circ)
  1466. {
  1467. int n = 0;
  1468. if (circ && circ->cpath) {
  1469. crypt_path_t *cpath, *cpath_next = NULL;
  1470. for (cpath = circ->cpath; cpath_next != circ->cpath; cpath = cpath_next) {
  1471. cpath_next = cpath->next;
  1472. ++n;
  1473. }
  1474. }
  1475. return n;
  1476. }
  1477. /** Return the <b>hopnum</b>th hop in <b>circ</b>->cpath, or NULL if there
  1478. * aren't that many hops in the list. <b>hopnum</b> starts at 1.
  1479. * Returns NULL if <b>hopnum</b> is 0 or negative. */
  1480. crypt_path_t *
  1481. circuit_get_cpath_hop(origin_circuit_t *circ, int hopnum)
  1482. {
  1483. if (circ && circ->cpath && hopnum > 0) {
  1484. crypt_path_t *cpath, *cpath_next = NULL;
  1485. for (cpath = circ->cpath; cpath_next != circ->cpath; cpath = cpath_next) {
  1486. cpath_next = cpath->next;
  1487. if (--hopnum <= 0)
  1488. return cpath;
  1489. }
  1490. }
  1491. return NULL;
  1492. }
  1493. /** Go through the circuitlist; mark-for-close each circuit that starts
  1494. * at us but has not yet been used. */
  1495. void
  1496. circuit_mark_all_unused_circs(void)
  1497. {
  1498. SMARTLIST_FOREACH_BEGIN(circuit_get_global_list(), circuit_t *, circ) {
  1499. if (CIRCUIT_IS_ORIGIN(circ) &&
  1500. !circ->marked_for_close &&
  1501. !circ->timestamp_dirty)
  1502. circuit_mark_for_close(circ, END_CIRC_REASON_FINISHED);
  1503. }
  1504. SMARTLIST_FOREACH_END(circ);
  1505. }
  1506. /** Go through the circuitlist; for each circuit that starts at us
  1507. * and is dirty, frob its timestamp_dirty so we won't use it for any
  1508. * new streams.
  1509. *
  1510. * This is useful for letting the user change pseudonyms, so new
  1511. * streams will not be linkable to old streams.
  1512. */
  1513. void
  1514. circuit_mark_all_dirty_circs_as_unusable(void)
  1515. {
  1516. SMARTLIST_FOREACH_BEGIN(circuit_get_global_list(), circuit_t *, circ) {
  1517. if (CIRCUIT_IS_ORIGIN(circ) &&
  1518. !circ->marked_for_close &&
  1519. circ->timestamp_dirty) {
  1520. mark_circuit_unusable_for_new_conns(TO_ORIGIN_CIRCUIT(circ));
  1521. }
  1522. }
  1523. SMARTLIST_FOREACH_END(circ);
  1524. }
  1525. /** Mark <b>circ</b> to be closed next time we call
  1526. * circuit_close_all_marked(). Do any cleanup needed:
  1527. * - If state is onionskin_pending, remove circ from the onion_pending
  1528. * list.
  1529. * - If circ isn't open yet: call circuit_build_failed() if we're
  1530. * the origin, and in either case call circuit_rep_hist_note_result()
  1531. * to note stats.
  1532. * - If purpose is C_INTRODUCE_ACK_WAIT, report the intro point
  1533. * failure we just had to the hidden service client module.
  1534. * - If purpose is C_INTRODUCING and <b>reason</b> isn't TIMEOUT,
  1535. * report to the hidden service client module that the intro point
  1536. * we just tried may be unreachable.
  1537. * - Send appropriate destroys and edge_destroys for conns and
  1538. * streams attached to circ.
  1539. * - If circ->rend_splice is set (we are the midpoint of a joined
  1540. * rendezvous stream), then mark the other circuit to close as well.
  1541. */
  1542. MOCK_IMPL(void,
  1543. circuit_mark_for_close_, (circuit_t *circ, int reason, int line,
  1544. const char *file))
  1545. {
  1546. int orig_reason = reason; /* Passed to the controller */
  1547. assert_circuit_ok(circ);
  1548. tor_assert(line);
  1549. tor_assert(file);
  1550. if (circ->marked_for_close) {
  1551. log_warn(LD_BUG,
  1552. "Duplicate call to circuit_mark_for_close at %s:%d"
  1553. " (first at %s:%d)", file, line,
  1554. circ->marked_for_close_file, circ->marked_for_close);
  1555. return;
  1556. }
  1557. if (reason == END_CIRC_AT_ORIGIN) {
  1558. if (!CIRCUIT_IS_ORIGIN(circ)) {
  1559. log_warn(LD_BUG, "Specified 'at-origin' non-reason for ending circuit, "
  1560. "but circuit was not at origin. (called %s:%d, purpose=%d)",
  1561. file, line, circ->purpose);
  1562. }
  1563. reason = END_CIRC_REASON_NONE;
  1564. }
  1565. if (CIRCUIT_IS_ORIGIN(circ)) {
  1566. if (pathbias_check_close(TO_ORIGIN_CIRCUIT(circ), reason) == -1) {
  1567. /* Don't close it yet, we need to test it first */
  1568. return;
  1569. }
  1570. /* We don't send reasons when closing circuits at the origin. */
  1571. reason = END_CIRC_REASON_NONE;
  1572. }
  1573. if (reason & END_CIRC_REASON_FLAG_REMOTE)
  1574. reason &= ~END_CIRC_REASON_FLAG_REMOTE;
  1575. if (reason < END_CIRC_REASON_MIN_ || reason > END_CIRC_REASON_MAX_) {
  1576. if (!(orig_reason & END_CIRC_REASON_FLAG_REMOTE))
  1577. log_warn(LD_BUG, "Reason %d out of range at %s:%d", reason, file, line);
  1578. reason = END_CIRC_REASON_NONE;
  1579. }
  1580. circ->marked_for_close = line;
  1581. circ->marked_for_close_file = file;
  1582. circ->marked_for_close_reason = reason;
  1583. circ->marked_for_close_orig_reason = orig_reason;
  1584. if (!CIRCUIT_IS_ORIGIN(circ)) {
  1585. or_circuit_t *or_circ = TO_OR_CIRCUIT(circ);
  1586. if (or_circ->rend_splice) {
  1587. if (!or_circ->rend_splice->base_.marked_for_close) {
  1588. /* do this after marking this circuit, to avoid infinite recursion. */
  1589. circuit_mark_for_close(TO_CIRCUIT(or_circ->rend_splice), reason);
  1590. }
  1591. or_circ->rend_splice = NULL;
  1592. }
  1593. }
  1594. if (circuits_pending_close == NULL)
  1595. circuits_pending_close = smartlist_new();
  1596. smartlist_add(circuits_pending_close, circ);
  1597. }
  1598. /** Called immediately before freeing a marked circuit <b>circ</b> from
  1599. * circuit_free_all() while shutting down Tor; this is a safe-at-shutdown
  1600. * version of circuit_about_to_free(). It's important that it at least
  1601. * do circuitmux_detach_circuit() when appropriate.
  1602. */
  1603. static void
  1604. circuit_about_to_free_atexit(circuit_t *circ)
  1605. {
  1606. if (circ->n_chan) {
  1607. circuit_clear_cell_queue(circ, circ->n_chan);
  1608. circuitmux_detach_circuit(circ->n_chan->cmux, circ);
  1609. circuit_set_n_circid_chan(circ, 0, NULL);
  1610. }
  1611. if (! CIRCUIT_IS_ORIGIN(circ)) {
  1612. or_circuit_t *or_circ = TO_OR_CIRCUIT(circ);
  1613. if (or_circ->p_chan) {
  1614. circuit_clear_cell_queue(circ, or_circ->p_chan);
  1615. circuitmux_detach_circuit(or_circ->p_chan->cmux, circ);
  1616. circuit_set_p_circid_chan(or_circ, 0, NULL);
  1617. }
  1618. }
  1619. }
  1620. /** Called immediately before freeing a marked circuit <b>circ</b>.
  1621. * Disconnects the circuit from other data structures, launches events
  1622. * as appropriate, and performs other housekeeping.
  1623. */
  1624. static void
  1625. circuit_about_to_free(circuit_t *circ)
  1626. {
  1627. int reason = circ->marked_for_close_reason;
  1628. int orig_reason = circ->marked_for_close_orig_reason;
  1629. if (circ->state == CIRCUIT_STATE_ONIONSKIN_PENDING) {
  1630. onion_pending_remove(TO_OR_CIRCUIT(circ));
  1631. }
  1632. /* If the circuit ever became OPEN, we sent it to the reputation history
  1633. * module then. If it isn't OPEN, we send it there now to remember which
  1634. * links worked and which didn't.
  1635. */
  1636. if (circ->state != CIRCUIT_STATE_OPEN &&
  1637. circ->state != CIRCUIT_STATE_GUARD_WAIT) {
  1638. if (CIRCUIT_IS_ORIGIN(circ)) {
  1639. origin_circuit_t *ocirc = TO_ORIGIN_CIRCUIT(circ);
  1640. circuit_build_failed(ocirc); /* take actions if necessary */
  1641. circuit_rep_hist_note_result(ocirc);
  1642. }
  1643. }
  1644. if (circ->state == CIRCUIT_STATE_CHAN_WAIT) {
  1645. if (circuits_pending_chans)
  1646. smartlist_remove(circuits_pending_chans, circ);
  1647. }
  1648. if (circuits_pending_other_guards) {
  1649. smartlist_remove(circuits_pending_other_guards, circ);
  1650. }
  1651. if (CIRCUIT_IS_ORIGIN(circ)) {
  1652. control_event_circuit_status(TO_ORIGIN_CIRCUIT(circ),
  1653. (circ->state == CIRCUIT_STATE_OPEN ||
  1654. circ->state == CIRCUIT_STATE_GUARD_WAIT) ?
  1655. CIRC_EVENT_CLOSED:CIRC_EVENT_FAILED,
  1656. orig_reason);
  1657. }
  1658. if (circ->purpose == CIRCUIT_PURPOSE_C_INTRODUCE_ACK_WAIT) {
  1659. origin_circuit_t *ocirc = TO_ORIGIN_CIRCUIT(circ);
  1660. int timed_out = (reason == END_CIRC_REASON_TIMEOUT);
  1661. tor_assert(circ->state == CIRCUIT_STATE_OPEN);
  1662. tor_assert(ocirc->build_state->chosen_exit);
  1663. tor_assert(ocirc->rend_data);
  1664. if (orig_reason != END_CIRC_REASON_IP_NOW_REDUNDANT) {
  1665. /* treat this like getting a nack from it */
  1666. log_info(LD_REND, "Failed intro circ %s to %s (awaiting ack). %s",
  1667. safe_str_client(rend_data_get_address(ocirc->rend_data)),
  1668. safe_str_client(build_state_get_exit_nickname(ocirc->build_state)),
  1669. timed_out ? "Recording timeout." : "Removing from descriptor.");
  1670. rend_client_report_intro_point_failure(ocirc->build_state->chosen_exit,
  1671. ocirc->rend_data,
  1672. timed_out ?
  1673. INTRO_POINT_FAILURE_TIMEOUT :
  1674. INTRO_POINT_FAILURE_GENERIC);
  1675. }
  1676. } else if (circ->purpose == CIRCUIT_PURPOSE_C_INTRODUCING &&
  1677. reason != END_CIRC_REASON_TIMEOUT) {
  1678. origin_circuit_t *ocirc = TO_ORIGIN_CIRCUIT(circ);
  1679. if (ocirc->build_state->chosen_exit && ocirc->rend_data) {
  1680. if (orig_reason != END_CIRC_REASON_IP_NOW_REDUNDANT) {
  1681. log_info(LD_REND, "Failed intro circ %s to %s "
  1682. "(building circuit to intro point). "
  1683. "Marking intro point as possibly unreachable.",
  1684. safe_str_client(rend_data_get_address(ocirc->rend_data)),
  1685. safe_str_client(build_state_get_exit_nickname(
  1686. ocirc->build_state)));
  1687. rend_client_report_intro_point_failure(ocirc->build_state->chosen_exit,
  1688. ocirc->rend_data,
  1689. INTRO_POINT_FAILURE_UNREACHABLE);
  1690. }
  1691. }
  1692. }
  1693. if (circ->n_chan) {
  1694. circuit_clear_cell_queue(circ, circ->n_chan);
  1695. /* Only send destroy if the channel isn't closing anyway */
  1696. if (!CHANNEL_CONDEMNED(circ->n_chan)) {
  1697. channel_send_destroy(circ->n_circ_id, circ->n_chan, reason);
  1698. }
  1699. circuitmux_detach_circuit(circ->n_chan->cmux, circ);
  1700. circuit_set_n_circid_chan(circ, 0, NULL);
  1701. }
  1702. if (! CIRCUIT_IS_ORIGIN(circ)) {
  1703. or_circuit_t *or_circ = TO_OR_CIRCUIT(circ);
  1704. edge_connection_t *conn;
  1705. for (conn=or_circ->n_streams; conn; conn=conn->next_stream)
  1706. connection_edge_destroy(or_circ->p_circ_id, conn);
  1707. or_circ->n_streams = NULL;
  1708. while (or_circ->resolving_streams) {
  1709. conn = or_circ->resolving_streams;
  1710. or_circ->resolving_streams = conn->next_stream;
  1711. if (!conn->base_.marked_for_close) {
  1712. /* The client will see a DESTROY, and infer that the connections
  1713. * are closing because the circuit is getting torn down. No need
  1714. * to send an end cell. */
  1715. conn->edge_has_sent_end = 1;
  1716. conn->end_reason = END_STREAM_REASON_DESTROY;
  1717. conn->end_reason |= END_STREAM_REASON_FLAG_ALREADY_SENT_CLOSED;
  1718. connection_mark_for_close(TO_CONN(conn));
  1719. }
  1720. conn->on_circuit = NULL;
  1721. }
  1722. if (or_circ->p_chan) {
  1723. circuit_clear_cell_queue(circ, or_circ->p_chan);
  1724. /* Only send destroy if the channel isn't closing anyway */
  1725. if (!CHANNEL_CONDEMNED(or_circ->p_chan)) {
  1726. channel_send_destroy(or_circ->p_circ_id, or_circ->p_chan, reason);
  1727. }
  1728. circuitmux_detach_circuit(or_circ->p_chan->cmux, circ);
  1729. circuit_set_p_circid_chan(or_circ, 0, NULL);
  1730. }
  1731. } else {
  1732. origin_circuit_t *ocirc = TO_ORIGIN_CIRCUIT(circ);
  1733. edge_connection_t *conn;
  1734. for (conn=ocirc->p_streams; conn; conn=conn->next_stream)
  1735. connection_edge_destroy(circ->n_circ_id, conn);
  1736. ocirc->p_streams = NULL;
  1737. }
  1738. }
  1739. /** Given a marked circuit <b>circ</b>, aggressively free its cell queues to
  1740. * recover memory. */
  1741. static void
  1742. marked_circuit_free_cells(circuit_t *circ)
  1743. {
  1744. if (!circ->marked_for_close) {
  1745. log_warn(LD_BUG, "Called on non-marked circuit");
  1746. return;
  1747. }
  1748. cell_queue_clear(&circ->n_chan_cells);
  1749. if (circ->n_mux)
  1750. circuitmux_clear_num_cells(circ->n_mux, circ);
  1751. if (! CIRCUIT_IS_ORIGIN(circ)) {
  1752. or_circuit_t *orcirc = TO_OR_CIRCUIT(circ);
  1753. cell_queue_clear(&orcirc->p_chan_cells);
  1754. if (orcirc->p_mux)
  1755. circuitmux_clear_num_cells(orcirc->p_mux, circ);
  1756. }
  1757. }
  1758. static size_t
  1759. single_conn_free_bytes(connection_t *conn)
  1760. {
  1761. size_t result = 0;
  1762. if (conn->inbuf) {
  1763. result += buf_allocation(conn->inbuf);
  1764. buf_clear(conn->inbuf);
  1765. }
  1766. if (conn->outbuf) {
  1767. result += buf_allocation(conn->outbuf);
  1768. buf_clear(conn->outbuf);
  1769. conn->outbuf_flushlen = 0;
  1770. }
  1771. if (conn->type == CONN_TYPE_DIR) {
  1772. dir_connection_t *dir_conn = TO_DIR_CONN(conn);
  1773. if (dir_conn->zlib_state) {
  1774. result += tor_zlib_state_size(dir_conn->zlib_state);
  1775. tor_zlib_free(dir_conn->zlib_state);
  1776. dir_conn->zlib_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. }