circuitlist.c 78 KB

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