circuitlist.c 76 KB

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