circuitlist.c 81 KB

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