circuitlist.c 78 KB

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