circuitlist.c 81 KB

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