circuitlist.c 82 KB

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