circuitlist.c 78 KB

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