circuitlist.c 82 KB

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