circuitlist.c 85 KB

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