circuitlist.c 77 KB

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