circuitlist.c 80 KB

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