circuitlist.c 74 KB

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