circuitlist.c 58 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836
  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-2013, The Tor Project, Inc. */
  5. /* See LICENSE for licensing information */
  6. /**
  7. * \file circuitlist.c
  8. * \brief Manage the global circuit list.
  9. **/
  10. #define CIRCUITLIST_PRIVATE
  11. #include "or.h"
  12. #include "channel.h"
  13. #include "circpathbias.h"
  14. #include "circuitbuild.h"
  15. #include "circuitlist.h"
  16. #include "circuituse.h"
  17. #include "circuitstats.h"
  18. #include "connection.h"
  19. #include "config.h"
  20. #include "connection_edge.h"
  21. #include "connection_or.h"
  22. #include "control.h"
  23. #include "networkstatus.h"
  24. #include "nodelist.h"
  25. #include "onion.h"
  26. #include "onion_fast.h"
  27. #include "policies.h"
  28. #include "relay.h"
  29. #include "rendclient.h"
  30. #include "rendcommon.h"
  31. #include "rephist.h"
  32. #include "routerlist.h"
  33. #include "routerset.h"
  34. #include "ht.h"
  35. /********* START VARIABLES **********/
  36. /** A global list of all circuits at this hop. */
  37. struct global_circuitlist_s global_circuitlist =
  38. TOR_LIST_HEAD_INITIALIZER(global_circuitlist);
  39. /** A list of all the circuits in CIRCUIT_STATE_CHAN_WAIT. */
  40. static smartlist_t *circuits_pending_chans = NULL;
  41. static void circuit_free_cpath(crypt_path_t *cpath);
  42. static void circuit_free_cpath_node(crypt_path_t *victim);
  43. static void cpath_ref_decref(crypt_path_reference_t *cpath_ref);
  44. /********* END VARIABLES ************/
  45. /** A map from channel and circuit ID to circuit. (Lookup performance is
  46. * very important here, since we need to do it every time a cell arrives.) */
  47. typedef struct chan_circid_circuit_map_t {
  48. HT_ENTRY(chan_circid_circuit_map_t) node;
  49. channel_t *chan;
  50. circid_t circ_id;
  51. circuit_t *circuit;
  52. } chan_circid_circuit_map_t;
  53. /** Helper for hash tables: compare the channel and circuit ID for a and
  54. * b, and return less than, equal to, or greater than zero appropriately.
  55. */
  56. static INLINE int
  57. chan_circid_entries_eq_(chan_circid_circuit_map_t *a,
  58. chan_circid_circuit_map_t *b)
  59. {
  60. return a->chan == b->chan && a->circ_id == b->circ_id;
  61. }
  62. /** Helper: return a hash based on circuit ID and the pointer value of
  63. * chan in <b>a</b>. */
  64. static INLINE unsigned int
  65. chan_circid_entry_hash_(chan_circid_circuit_map_t *a)
  66. {
  67. return ((unsigned)a->circ_id) ^ (unsigned)(uintptr_t)(a->chan);
  68. }
  69. /** Map from [chan,circid] to circuit. */
  70. static HT_HEAD(chan_circid_map, chan_circid_circuit_map_t)
  71. chan_circid_map = HT_INITIALIZER();
  72. HT_PROTOTYPE(chan_circid_map, chan_circid_circuit_map_t, node,
  73. chan_circid_entry_hash_, chan_circid_entries_eq_)
  74. HT_GENERATE(chan_circid_map, chan_circid_circuit_map_t, node,
  75. chan_circid_entry_hash_, chan_circid_entries_eq_, 0.6,
  76. malloc, realloc, free)
  77. /** The most recently returned entry from circuit_get_by_circid_chan;
  78. * used to improve performance when many cells arrive in a row from the
  79. * same circuit.
  80. */
  81. chan_circid_circuit_map_t *_last_circid_chan_ent = NULL;
  82. /** Implementation helper for circuit_set_{p,n}_circid_channel: A circuit ID
  83. * and/or channel for circ has just changed from <b>old_chan, old_id</b>
  84. * to <b>chan, id</b>. Adjust the chan,circid map as appropriate, removing
  85. * the old entry (if any) and adding a new one. */
  86. static void
  87. circuit_set_circid_chan_helper(circuit_t *circ, int direction,
  88. circid_t id,
  89. channel_t *chan)
  90. {
  91. chan_circid_circuit_map_t search;
  92. chan_circid_circuit_map_t *found;
  93. channel_t *old_chan, **chan_ptr;
  94. circid_t old_id, *circid_ptr;
  95. int make_active, attached = 0;
  96. if (direction == CELL_DIRECTION_OUT) {
  97. chan_ptr = &circ->n_chan;
  98. circid_ptr = &circ->n_circ_id;
  99. make_active = circ->n_chan_cells.n > 0;
  100. } else {
  101. or_circuit_t *c = TO_OR_CIRCUIT(circ);
  102. chan_ptr = &c->p_chan;
  103. circid_ptr = &c->p_circ_id;
  104. make_active = c->p_chan_cells.n > 0;
  105. }
  106. old_chan = *chan_ptr;
  107. old_id = *circid_ptr;
  108. if (id == old_id && chan == old_chan)
  109. return;
  110. if (_last_circid_chan_ent &&
  111. ((old_id == _last_circid_chan_ent->circ_id &&
  112. old_chan == _last_circid_chan_ent->chan) ||
  113. (id == _last_circid_chan_ent->circ_id &&
  114. chan == _last_circid_chan_ent->chan))) {
  115. _last_circid_chan_ent = NULL;
  116. }
  117. if (old_chan) {
  118. /*
  119. * If we're changing channels or ID and had an old channel and a non
  120. * zero old ID and weren't marked for close (i.e., we should have been
  121. * attached), detach the circuit. ID changes require this because
  122. * circuitmux hashes on (channel_id, circuit_id).
  123. */
  124. if (old_id != 0 && (old_chan != chan || old_id != id) &&
  125. !(circ->marked_for_close)) {
  126. tor_assert(old_chan->cmux);
  127. circuitmux_detach_circuit(old_chan->cmux, circ);
  128. }
  129. /* we may need to remove it from the conn-circid map */
  130. search.circ_id = old_id;
  131. search.chan = old_chan;
  132. found = HT_REMOVE(chan_circid_map, &chan_circid_map, &search);
  133. if (found) {
  134. tor_free(found);
  135. if (direction == CELL_DIRECTION_OUT) {
  136. /* One fewer circuits use old_chan as n_chan */
  137. --(old_chan->num_n_circuits);
  138. } else {
  139. /* One fewer circuits use old_chan as p_chan */
  140. --(old_chan->num_p_circuits);
  141. }
  142. }
  143. }
  144. /* Change the values only after we have possibly made the circuit inactive
  145. * on the previous chan. */
  146. *chan_ptr = chan;
  147. *circid_ptr = id;
  148. if (chan == NULL)
  149. return;
  150. /* now add the new one to the conn-circid map */
  151. search.circ_id = id;
  152. search.chan = chan;
  153. found = HT_FIND(chan_circid_map, &chan_circid_map, &search);
  154. if (found) {
  155. found->circuit = circ;
  156. } else {
  157. found = tor_malloc_zero(sizeof(chan_circid_circuit_map_t));
  158. found->circ_id = id;
  159. found->chan = chan;
  160. found->circuit = circ;
  161. HT_INSERT(chan_circid_map, &chan_circid_map, found);
  162. }
  163. /*
  164. * Attach to the circuitmux if we're changing channels or IDs and
  165. * have a new channel and ID to use and the circuit is not marked for
  166. * close.
  167. */
  168. if (chan && id != 0 && (old_chan != chan || old_id != id) &&
  169. !(circ->marked_for_close)) {
  170. tor_assert(chan->cmux);
  171. circuitmux_attach_circuit(chan->cmux, circ, direction);
  172. attached = 1;
  173. }
  174. /*
  175. * This is a no-op if we have no cells, but if we do it marks us active to
  176. * the circuitmux
  177. */
  178. if (make_active && attached)
  179. update_circuit_on_cmux(circ, direction);
  180. /* Adjust circuit counts on new channel */
  181. if (direction == CELL_DIRECTION_OUT) {
  182. ++chan->num_n_circuits;
  183. } else {
  184. ++chan->num_p_circuits;
  185. }
  186. }
  187. /** Mark that circuit id <b>id</b> shouldn't be used on channel <b>chan</b>,
  188. * even if there is no circuit on the channel. We use this to keep the
  189. * circuit id from getting re-used while we have queued but not yet sent
  190. * a destroy cell. */
  191. void
  192. channel_mark_circid_unusable(channel_t *chan, circid_t id)
  193. {
  194. chan_circid_circuit_map_t search;
  195. chan_circid_circuit_map_t *ent;
  196. /* See if there's an entry there. That wouldn't be good. */
  197. memset(&search, 0, sizeof(search));
  198. search.chan = chan;
  199. search.circ_id = id;
  200. ent = HT_FIND(chan_circid_map, &chan_circid_map, &search);
  201. if (ent && ent->circuit) {
  202. /* we have a problem. */
  203. log_warn(LD_BUG, "Tried to mark %u unusable on %p, but there was already "
  204. "a circuit there.", (unsigned)id, chan);
  205. } else if (ent) {
  206. /* It's already marked. */
  207. } else {
  208. ent = tor_malloc_zero(sizeof(chan_circid_circuit_map_t));
  209. ent->chan = chan;
  210. ent->circ_id = id;
  211. /* leave circuit at NULL */
  212. HT_INSERT(chan_circid_map, &chan_circid_map, ent);
  213. }
  214. }
  215. /** Mark that a circuit id <b>id</b> can be used again on <b>chan</b>.
  216. * We use this to re-enable the circuit ID after we've sent a destroy cell.
  217. */
  218. void
  219. channel_mark_circid_usable(channel_t *chan, circid_t id)
  220. {
  221. chan_circid_circuit_map_t search;
  222. chan_circid_circuit_map_t *ent;
  223. /* See if there's an entry there. That wouldn't be good. */
  224. memset(&search, 0, sizeof(search));
  225. search.chan = chan;
  226. search.circ_id = id;
  227. ent = HT_REMOVE(chan_circid_map, &chan_circid_map, &search);
  228. if (ent && ent->circuit) {
  229. log_warn(LD_BUG, "Tried to mark %u usable on %p, but there was already "
  230. "a circuit there.", (unsigned)id, chan);
  231. return;
  232. }
  233. if (_last_circid_chan_ent == ent)
  234. _last_circid_chan_ent = NULL;
  235. tor_free(ent);
  236. }
  237. /** Called to indicate that a DESTROY is pending on <b>chan</b> with
  238. * circuit ID <b>id</b>, but hasn't been sent yet. */
  239. void
  240. channel_note_destroy_pending(channel_t *chan, circid_t id)
  241. {
  242. circuit_t *circ = circuit_get_by_circid_channel_even_if_marked(id,chan);
  243. if (circ) {
  244. if (circ->n_chan == chan && circ->n_circ_id == id) {
  245. circ->n_delete_pending = 1;
  246. } else {
  247. or_circuit_t *orcirc = TO_OR_CIRCUIT(circ);
  248. if (orcirc->p_chan == chan && orcirc->p_circ_id == id) {
  249. circ->p_delete_pending = 1;
  250. }
  251. }
  252. return;
  253. }
  254. channel_mark_circid_unusable(chan, id);
  255. }
  256. /** Called to indicate that a DESTROY is no longer pending on <b>chan</b> with
  257. * circuit ID <b>id</b> -- typically, because it has been sent. */
  258. void
  259. channel_note_destroy_not_pending(channel_t *chan, circid_t id)
  260. {
  261. circuit_t *circ = circuit_get_by_circid_channel_even_if_marked(id,chan);
  262. if (circ) {
  263. if (circ->n_chan == chan && circ->n_circ_id == id) {
  264. circ->n_delete_pending = 0;
  265. } else {
  266. or_circuit_t *orcirc = TO_OR_CIRCUIT(circ);
  267. if (orcirc->p_chan == chan && orcirc->p_circ_id == id) {
  268. circ->p_delete_pending = 0;
  269. }
  270. }
  271. /* XXXX this shouldn't happen; log a bug here. */
  272. return;
  273. }
  274. channel_mark_circid_usable(chan, id);
  275. }
  276. /** Set the p_conn field of a circuit <b>circ</b>, along
  277. * with the corresponding circuit ID, and add the circuit as appropriate
  278. * to the (chan,id)-\>circuit map. */
  279. void
  280. circuit_set_p_circid_chan(or_circuit_t *or_circ, circid_t id,
  281. channel_t *chan)
  282. {
  283. circuit_t *circ = TO_CIRCUIT(or_circ);
  284. channel_t *old_chan = or_circ->p_chan;
  285. circid_t old_id = or_circ->p_circ_id;
  286. circuit_set_circid_chan_helper(circ, CELL_DIRECTION_IN, id, chan);
  287. if (chan)
  288. tor_assert(bool_eq(or_circ->p_chan_cells.n,
  289. or_circ->next_active_on_p_chan));
  290. if (circ->p_delete_pending && old_chan) {
  291. channel_mark_circid_unusable(old_chan, old_id);
  292. circ->p_delete_pending = 0;
  293. }
  294. }
  295. /** Set the n_conn field of a circuit <b>circ</b>, along
  296. * with the corresponding circuit ID, and add the circuit as appropriate
  297. * to the (chan,id)-\>circuit map. */
  298. void
  299. circuit_set_n_circid_chan(circuit_t *circ, circid_t id,
  300. channel_t *chan)
  301. {
  302. channel_t *old_chan = circ->n_chan;
  303. circid_t old_id = circ->n_circ_id;
  304. circuit_set_circid_chan_helper(circ, CELL_DIRECTION_OUT, id, chan);
  305. if (chan)
  306. tor_assert(bool_eq(circ->n_chan_cells.n, circ->next_active_on_n_chan));
  307. if (circ->n_delete_pending && old_chan) {
  308. channel_mark_circid_unusable(old_chan, old_id);
  309. circ->n_delete_pending = 0;
  310. }
  311. }
  312. /** Change the state of <b>circ</b> to <b>state</b>, adding it to or removing
  313. * it from lists as appropriate. */
  314. void
  315. circuit_set_state(circuit_t *circ, uint8_t state)
  316. {
  317. tor_assert(circ);
  318. if (state == circ->state)
  319. return;
  320. if (!circuits_pending_chans)
  321. circuits_pending_chans = smartlist_new();
  322. if (circ->state == CIRCUIT_STATE_CHAN_WAIT) {
  323. /* remove from waiting-circuit list. */
  324. smartlist_remove(circuits_pending_chans, circ);
  325. }
  326. if (state == CIRCUIT_STATE_CHAN_WAIT) {
  327. /* add to waiting-circuit list. */
  328. smartlist_add(circuits_pending_chans, circ);
  329. }
  330. if (state == CIRCUIT_STATE_OPEN)
  331. tor_assert(!circ->n_chan_create_cell);
  332. circ->state = state;
  333. }
  334. /** Append to <b>out</b> all circuits in state CHAN_WAIT waiting for
  335. * the given connection. */
  336. void
  337. circuit_get_all_pending_on_channel(smartlist_t *out, channel_t *chan)
  338. {
  339. tor_assert(out);
  340. tor_assert(chan);
  341. if (!circuits_pending_chans)
  342. return;
  343. SMARTLIST_FOREACH_BEGIN(circuits_pending_chans, circuit_t *, circ) {
  344. if (circ->marked_for_close)
  345. continue;
  346. if (!circ->n_hop)
  347. continue;
  348. tor_assert(circ->state == CIRCUIT_STATE_CHAN_WAIT);
  349. if (tor_digest_is_zero(circ->n_hop->identity_digest)) {
  350. /* Look at addr/port. This is an unkeyed connection. */
  351. if (!channel_matches_extend_info(chan, circ->n_hop))
  352. continue;
  353. } else {
  354. /* We expected a key. See if it's the right one. */
  355. if (tor_memneq(chan->identity_digest,
  356. circ->n_hop->identity_digest, DIGEST_LEN))
  357. continue;
  358. }
  359. smartlist_add(out, circ);
  360. } SMARTLIST_FOREACH_END(circ);
  361. }
  362. /** Return the number of circuits in state CHAN_WAIT, waiting for the given
  363. * channel. */
  364. int
  365. circuit_count_pending_on_channel(channel_t *chan)
  366. {
  367. int cnt;
  368. smartlist_t *sl = smartlist_new();
  369. tor_assert(chan);
  370. circuit_get_all_pending_on_channel(sl, chan);
  371. cnt = smartlist_len(sl);
  372. smartlist_free(sl);
  373. log_debug(LD_CIRC,"or_conn to %s at %s, %d pending circs",
  374. chan->nickname ? chan->nickname : "NULL",
  375. channel_get_canonical_remote_descr(chan),
  376. cnt);
  377. return cnt;
  378. }
  379. /** Detach from the global circuit list, and deallocate, all
  380. * circuits that have been marked for close.
  381. */
  382. void
  383. circuit_close_all_marked(void)
  384. {
  385. circuit_t *circ, *tmp;
  386. TOR_LIST_FOREACH_SAFE(circ, &global_circuitlist, head, tmp)
  387. if (circ->marked_for_close)
  388. circuit_free(circ);
  389. }
  390. /** Return the head of the global linked list of circuits. */
  391. struct global_circuitlist_s *
  392. circuit_get_global_list(void)
  393. {
  394. return &global_circuitlist;
  395. }
  396. /** Function to make circ-\>state human-readable */
  397. const char *
  398. circuit_state_to_string(int state)
  399. {
  400. static char buf[64];
  401. switch (state) {
  402. case CIRCUIT_STATE_BUILDING: return "doing handshakes";
  403. case CIRCUIT_STATE_ONIONSKIN_PENDING: return "processing the onion";
  404. case CIRCUIT_STATE_CHAN_WAIT: return "connecting to server";
  405. case CIRCUIT_STATE_OPEN: return "open";
  406. default:
  407. log_warn(LD_BUG, "Unknown circuit state %d", state);
  408. tor_snprintf(buf, sizeof(buf), "unknown state [%d]", state);
  409. return buf;
  410. }
  411. }
  412. /** Map a circuit purpose to a string suitable to be displayed to a
  413. * controller. */
  414. const char *
  415. circuit_purpose_to_controller_string(uint8_t purpose)
  416. {
  417. static char buf[32];
  418. switch (purpose) {
  419. case CIRCUIT_PURPOSE_OR:
  420. case CIRCUIT_PURPOSE_INTRO_POINT:
  421. case CIRCUIT_PURPOSE_REND_POINT_WAITING:
  422. case CIRCUIT_PURPOSE_REND_ESTABLISHED:
  423. return "SERVER"; /* A controller should never see these, actually. */
  424. case CIRCUIT_PURPOSE_C_GENERAL:
  425. return "GENERAL";
  426. case CIRCUIT_PURPOSE_C_INTRODUCING:
  427. case CIRCUIT_PURPOSE_C_INTRODUCE_ACK_WAIT:
  428. case CIRCUIT_PURPOSE_C_INTRODUCE_ACKED:
  429. return "HS_CLIENT_INTRO";
  430. case CIRCUIT_PURPOSE_C_ESTABLISH_REND:
  431. case CIRCUIT_PURPOSE_C_REND_READY:
  432. case CIRCUIT_PURPOSE_C_REND_READY_INTRO_ACKED:
  433. case CIRCUIT_PURPOSE_C_REND_JOINED:
  434. return "HS_CLIENT_REND";
  435. case CIRCUIT_PURPOSE_S_ESTABLISH_INTRO:
  436. case CIRCUIT_PURPOSE_S_INTRO:
  437. return "HS_SERVICE_INTRO";
  438. case CIRCUIT_PURPOSE_S_CONNECT_REND:
  439. case CIRCUIT_PURPOSE_S_REND_JOINED:
  440. return "HS_SERVICE_REND";
  441. case CIRCUIT_PURPOSE_TESTING:
  442. return "TESTING";
  443. case CIRCUIT_PURPOSE_C_MEASURE_TIMEOUT:
  444. return "MEASURE_TIMEOUT";
  445. case CIRCUIT_PURPOSE_CONTROLLER:
  446. return "CONTROLLER";
  447. case CIRCUIT_PURPOSE_PATH_BIAS_TESTING:
  448. return "PATH_BIAS_TESTING";
  449. default:
  450. tor_snprintf(buf, sizeof(buf), "UNKNOWN_%d", (int)purpose);
  451. return buf;
  452. }
  453. }
  454. /** Return a string specifying the state of the hidden-service circuit
  455. * purpose <b>purpose</b>, or NULL if <b>purpose</b> is not a
  456. * hidden-service-related circuit purpose. */
  457. const char *
  458. circuit_purpose_to_controller_hs_state_string(uint8_t purpose)
  459. {
  460. switch (purpose)
  461. {
  462. default:
  463. log_fn(LOG_WARN, LD_BUG,
  464. "Unrecognized circuit purpose: %d",
  465. (int)purpose);
  466. tor_fragile_assert();
  467. /* fall through */
  468. case CIRCUIT_PURPOSE_OR:
  469. case CIRCUIT_PURPOSE_C_GENERAL:
  470. case CIRCUIT_PURPOSE_C_MEASURE_TIMEOUT:
  471. case CIRCUIT_PURPOSE_TESTING:
  472. case CIRCUIT_PURPOSE_CONTROLLER:
  473. case CIRCUIT_PURPOSE_PATH_BIAS_TESTING:
  474. return NULL;
  475. case CIRCUIT_PURPOSE_INTRO_POINT:
  476. return "OR_HSSI_ESTABLISHED";
  477. case CIRCUIT_PURPOSE_REND_POINT_WAITING:
  478. return "OR_HSCR_ESTABLISHED";
  479. case CIRCUIT_PURPOSE_REND_ESTABLISHED:
  480. return "OR_HS_R_JOINED";
  481. case CIRCUIT_PURPOSE_C_INTRODUCING:
  482. return "HSCI_CONNECTING";
  483. case CIRCUIT_PURPOSE_C_INTRODUCE_ACK_WAIT:
  484. return "HSCI_INTRO_SENT";
  485. case CIRCUIT_PURPOSE_C_INTRODUCE_ACKED:
  486. return "HSCI_DONE";
  487. case CIRCUIT_PURPOSE_C_ESTABLISH_REND:
  488. return "HSCR_CONNECTING";
  489. case CIRCUIT_PURPOSE_C_REND_READY:
  490. return "HSCR_ESTABLISHED_IDLE";
  491. case CIRCUIT_PURPOSE_C_REND_READY_INTRO_ACKED:
  492. return "HSCR_ESTABLISHED_WAITING";
  493. case CIRCUIT_PURPOSE_C_REND_JOINED:
  494. return "HSCR_JOINED";
  495. case CIRCUIT_PURPOSE_S_ESTABLISH_INTRO:
  496. return "HSSI_CONNECTING";
  497. case CIRCUIT_PURPOSE_S_INTRO:
  498. return "HSSI_ESTABLISHED";
  499. case CIRCUIT_PURPOSE_S_CONNECT_REND:
  500. return "HSSR_CONNECTING";
  501. case CIRCUIT_PURPOSE_S_REND_JOINED:
  502. return "HSSR_JOINED";
  503. }
  504. }
  505. /** Return a human-readable string for the circuit purpose <b>purpose</b>. */
  506. const char *
  507. circuit_purpose_to_string(uint8_t purpose)
  508. {
  509. static char buf[32];
  510. switch (purpose)
  511. {
  512. case CIRCUIT_PURPOSE_OR:
  513. return "Circuit at relay";
  514. case CIRCUIT_PURPOSE_INTRO_POINT:
  515. return "Acting as intro point";
  516. case CIRCUIT_PURPOSE_REND_POINT_WAITING:
  517. return "Acting as rendevous (pending)";
  518. case CIRCUIT_PURPOSE_REND_ESTABLISHED:
  519. return "Acting as rendevous (established)";
  520. case CIRCUIT_PURPOSE_C_GENERAL:
  521. return "General-purpose client";
  522. case CIRCUIT_PURPOSE_C_INTRODUCING:
  523. return "Hidden service client: Connecting to intro point";
  524. case CIRCUIT_PURPOSE_C_INTRODUCE_ACK_WAIT:
  525. return "Hidden service client: Waiting for ack from intro point";
  526. case CIRCUIT_PURPOSE_C_INTRODUCE_ACKED:
  527. return "Hidden service client: Received ack from intro point";
  528. case CIRCUIT_PURPOSE_C_ESTABLISH_REND:
  529. return "Hidden service client: Establishing rendezvous point";
  530. case CIRCUIT_PURPOSE_C_REND_READY:
  531. return "Hidden service client: Pending rendezvous point";
  532. case CIRCUIT_PURPOSE_C_REND_READY_INTRO_ACKED:
  533. return "Hidden service client: Pending rendezvous point (ack received)";
  534. case CIRCUIT_PURPOSE_C_REND_JOINED:
  535. return "Hidden service client: Active rendezvous point";
  536. case CIRCUIT_PURPOSE_C_MEASURE_TIMEOUT:
  537. return "Measuring circuit timeout";
  538. case CIRCUIT_PURPOSE_S_ESTABLISH_INTRO:
  539. return "Hidden service: Establishing introduction point";
  540. case CIRCUIT_PURPOSE_S_INTRO:
  541. return "Hidden service: Introduction point";
  542. case CIRCUIT_PURPOSE_S_CONNECT_REND:
  543. return "Hidden service: Connecting to rendezvous point";
  544. case CIRCUIT_PURPOSE_S_REND_JOINED:
  545. return "Hidden service: Active rendezvous point";
  546. case CIRCUIT_PURPOSE_TESTING:
  547. return "Testing circuit";
  548. case CIRCUIT_PURPOSE_CONTROLLER:
  549. return "Circuit made by controller";
  550. case CIRCUIT_PURPOSE_PATH_BIAS_TESTING:
  551. return "Path-bias testing circuit";
  552. default:
  553. tor_snprintf(buf, sizeof(buf), "UNKNOWN_%d", (int)purpose);
  554. return buf;
  555. }
  556. }
  557. /** Pick a reasonable package_window to start out for our circuits.
  558. * Originally this was hard-coded at 1000, but now the consensus votes
  559. * on the answer. See proposal 168. */
  560. int32_t
  561. circuit_initial_package_window(void)
  562. {
  563. int32_t num = networkstatus_get_param(NULL, "circwindow", CIRCWINDOW_START,
  564. CIRCWINDOW_START_MIN,
  565. CIRCWINDOW_START_MAX);
  566. /* If the consensus tells us a negative number, we'd assert. */
  567. if (num < 0)
  568. num = CIRCWINDOW_START;
  569. return num;
  570. }
  571. /** Initialize the common elements in a circuit_t, and add it to the global
  572. * list. */
  573. static void
  574. init_circuit_base(circuit_t *circ)
  575. {
  576. tor_gettimeofday(&circ->timestamp_created);
  577. // Gets reset when we send CREATE_FAST.
  578. // circuit_expire_building() expects these to be equal
  579. // until the orconn is built.
  580. circ->timestamp_began = circ->timestamp_created;
  581. circ->package_window = circuit_initial_package_window();
  582. circ->deliver_window = CIRCWINDOW_START;
  583. cell_queue_init(&circ->n_chan_cells);
  584. TOR_LIST_INSERT_HEAD(&global_circuitlist, circ, head);
  585. }
  586. /** Allocate space for a new circuit, initializing with <b>p_circ_id</b>
  587. * and <b>p_conn</b>. Add it to the global circuit list.
  588. */
  589. origin_circuit_t *
  590. origin_circuit_new(void)
  591. {
  592. origin_circuit_t *circ;
  593. /* never zero, since a global ID of 0 is treated specially by the
  594. * controller */
  595. static uint32_t n_circuits_allocated = 1;
  596. circ = tor_malloc_zero(sizeof(origin_circuit_t));
  597. circ->base_.magic = ORIGIN_CIRCUIT_MAGIC;
  598. circ->next_stream_id = crypto_rand_int(1<<16);
  599. circ->global_identifier = n_circuits_allocated++;
  600. circ->remaining_relay_early_cells = MAX_RELAY_EARLY_CELLS_PER_CIRCUIT;
  601. circ->remaining_relay_early_cells -= crypto_rand_int(2);
  602. init_circuit_base(TO_CIRCUIT(circ));
  603. circuit_build_times_update_last_circ(get_circuit_build_times_mutable());
  604. return circ;
  605. }
  606. /** Allocate a new or_circuit_t, connected to <b>p_conn</b> as
  607. * <b>p_circ_id</b>. If <b>p_conn</b> is NULL, the circuit is unattached. */
  608. or_circuit_t *
  609. or_circuit_new(circid_t p_circ_id, channel_t *p_chan)
  610. {
  611. /* CircIDs */
  612. or_circuit_t *circ;
  613. circ = tor_malloc_zero(sizeof(or_circuit_t));
  614. circ->base_.magic = OR_CIRCUIT_MAGIC;
  615. if (p_chan)
  616. circuit_set_p_circid_chan(circ, p_circ_id, p_chan);
  617. circ->remaining_relay_early_cells = MAX_RELAY_EARLY_CELLS_PER_CIRCUIT;
  618. cell_queue_init(&circ->p_chan_cells);
  619. init_circuit_base(TO_CIRCUIT(circ));
  620. return circ;
  621. }
  622. /** Deallocate space associated with circ.
  623. */
  624. STATIC void
  625. circuit_free(circuit_t *circ)
  626. {
  627. void *mem;
  628. size_t memlen;
  629. if (!circ)
  630. return;
  631. if (CIRCUIT_IS_ORIGIN(circ)) {
  632. origin_circuit_t *ocirc = TO_ORIGIN_CIRCUIT(circ);
  633. mem = ocirc;
  634. memlen = sizeof(origin_circuit_t);
  635. tor_assert(circ->magic == ORIGIN_CIRCUIT_MAGIC);
  636. if (ocirc->build_state) {
  637. extend_info_free(ocirc->build_state->chosen_exit);
  638. circuit_free_cpath_node(ocirc->build_state->pending_final_cpath);
  639. cpath_ref_decref(ocirc->build_state->service_pending_final_cpath_ref);
  640. }
  641. tor_free(ocirc->build_state);
  642. circuit_free_cpath(ocirc->cpath);
  643. crypto_pk_free(ocirc->intro_key);
  644. rend_data_free(ocirc->rend_data);
  645. tor_free(ocirc->dest_address);
  646. if (ocirc->socks_username) {
  647. memwipe(ocirc->socks_username, 0x12, ocirc->socks_username_len);
  648. tor_free(ocirc->socks_username);
  649. }
  650. if (ocirc->socks_password) {
  651. memwipe(ocirc->socks_password, 0x06, ocirc->socks_password_len);
  652. tor_free(ocirc->socks_password);
  653. }
  654. addr_policy_list_free(ocirc->prepend_policy);
  655. } else {
  656. or_circuit_t *ocirc = TO_OR_CIRCUIT(circ);
  657. /* Remember cell statistics for this circuit before deallocating. */
  658. if (get_options()->CellStatistics)
  659. rep_hist_buffer_stats_add_circ(circ, time(NULL));
  660. mem = ocirc;
  661. memlen = sizeof(or_circuit_t);
  662. tor_assert(circ->magic == OR_CIRCUIT_MAGIC);
  663. crypto_cipher_free(ocirc->p_crypto);
  664. crypto_digest_free(ocirc->p_digest);
  665. crypto_cipher_free(ocirc->n_crypto);
  666. crypto_digest_free(ocirc->n_digest);
  667. if (ocirc->rend_splice) {
  668. or_circuit_t *other = ocirc->rend_splice;
  669. tor_assert(other->base_.magic == OR_CIRCUIT_MAGIC);
  670. other->rend_splice = NULL;
  671. }
  672. /* remove from map. */
  673. circuit_set_p_circid_chan(ocirc, 0, NULL);
  674. /* Clear cell queue _after_ removing it from the map. Otherwise our
  675. * "active" checks will be violated. */
  676. cell_queue_clear(&ocirc->p_chan_cells);
  677. }
  678. extend_info_free(circ->n_hop);
  679. tor_free(circ->n_chan_create_cell);
  680. TOR_LIST_REMOVE(circ, head);
  681. /* Remove from map. */
  682. circuit_set_n_circid_chan(circ, 0, NULL);
  683. /* Clear cell queue _after_ removing it from the map. Otherwise our
  684. * "active" checks will be violated. */
  685. cell_queue_clear(&circ->n_chan_cells);
  686. memwipe(mem, 0xAA, memlen); /* poison memory */
  687. tor_free(mem);
  688. }
  689. /** Deallocate space associated with the linked list <b>cpath</b>. */
  690. static void
  691. circuit_free_cpath(crypt_path_t *cpath)
  692. {
  693. crypt_path_t *victim, *head=cpath;
  694. if (!cpath)
  695. return;
  696. /* it's a doubly linked list, so we have to notice when we've
  697. * gone through it once. */
  698. while (cpath->next && cpath->next != head) {
  699. victim = cpath;
  700. cpath = victim->next;
  701. circuit_free_cpath_node(victim);
  702. }
  703. circuit_free_cpath_node(cpath);
  704. }
  705. /** Release all storage held by circuits. */
  706. void
  707. circuit_free_all(void)
  708. {
  709. circuit_t *tmp, *tmp2;
  710. TOR_LIST_FOREACH_SAFE(tmp, &global_circuitlist, head, tmp2) {
  711. if (! CIRCUIT_IS_ORIGIN(tmp)) {
  712. or_circuit_t *or_circ = TO_OR_CIRCUIT(tmp);
  713. while (or_circ->resolving_streams) {
  714. edge_connection_t *next_conn;
  715. next_conn = or_circ->resolving_streams->next_stream;
  716. connection_free(TO_CONN(or_circ->resolving_streams));
  717. or_circ->resolving_streams = next_conn;
  718. }
  719. }
  720. circuit_free(tmp);
  721. }
  722. smartlist_free(circuits_pending_chans);
  723. circuits_pending_chans = NULL;
  724. HT_CLEAR(chan_circid_map, &chan_circid_map);
  725. }
  726. /** Deallocate space associated with the cpath node <b>victim</b>. */
  727. static void
  728. circuit_free_cpath_node(crypt_path_t *victim)
  729. {
  730. if (!victim)
  731. return;
  732. crypto_cipher_free(victim->f_crypto);
  733. crypto_cipher_free(victim->b_crypto);
  734. crypto_digest_free(victim->f_digest);
  735. crypto_digest_free(victim->b_digest);
  736. onion_handshake_state_release(&victim->handshake_state);
  737. crypto_dh_free(victim->rend_dh_handshake_state);
  738. extend_info_free(victim->extend_info);
  739. memwipe(victim, 0xBB, sizeof(crypt_path_t)); /* poison memory */
  740. tor_free(victim);
  741. }
  742. /** Release a crypt_path_reference_t*, which may be NULL. */
  743. static void
  744. cpath_ref_decref(crypt_path_reference_t *cpath_ref)
  745. {
  746. if (cpath_ref != NULL) {
  747. if (--(cpath_ref->refcount) == 0) {
  748. circuit_free_cpath_node(cpath_ref->cpath);
  749. tor_free(cpath_ref);
  750. }
  751. }
  752. }
  753. /** A helper function for circuit_dump_by_conn() below. Log a bunch
  754. * of information about circuit <b>circ</b>.
  755. */
  756. static void
  757. circuit_dump_conn_details(int severity,
  758. circuit_t *circ,
  759. int conn_array_index,
  760. const char *type,
  761. circid_t this_circid,
  762. circid_t other_circid)
  763. {
  764. tor_log(severity, LD_CIRC, "Conn %d has %s circuit: circID %u "
  765. "(other side %u), state %d (%s), born %ld:",
  766. conn_array_index, type, (unsigned)this_circid, (unsigned)other_circid,
  767. circ->state, circuit_state_to_string(circ->state),
  768. (long)circ->timestamp_began.tv_sec);
  769. if (CIRCUIT_IS_ORIGIN(circ)) { /* circ starts at this node */
  770. circuit_log_path(severity, LD_CIRC, TO_ORIGIN_CIRCUIT(circ));
  771. }
  772. }
  773. /** Log, at severity <b>severity</b>, information about each circuit
  774. * that is connected to <b>conn</b>.
  775. */
  776. void
  777. circuit_dump_by_conn(connection_t *conn, int severity)
  778. {
  779. circuit_t *circ;
  780. edge_connection_t *tmpconn;
  781. TOR_LIST_FOREACH(circ, &global_circuitlist, head) {
  782. circid_t n_circ_id = circ->n_circ_id, p_circ_id = 0;
  783. if (circ->marked_for_close) {
  784. continue;
  785. }
  786. if (!CIRCUIT_IS_ORIGIN(circ)) {
  787. p_circ_id = TO_OR_CIRCUIT(circ)->p_circ_id;
  788. }
  789. if (CIRCUIT_IS_ORIGIN(circ)) {
  790. for (tmpconn=TO_ORIGIN_CIRCUIT(circ)->p_streams; tmpconn;
  791. tmpconn=tmpconn->next_stream) {
  792. if (TO_CONN(tmpconn) == conn) {
  793. circuit_dump_conn_details(severity, circ, conn->conn_array_index,
  794. "App-ward", p_circ_id, n_circ_id);
  795. }
  796. }
  797. }
  798. if (! CIRCUIT_IS_ORIGIN(circ)) {
  799. for (tmpconn=TO_OR_CIRCUIT(circ)->n_streams; tmpconn;
  800. tmpconn=tmpconn->next_stream) {
  801. if (TO_CONN(tmpconn) == conn) {
  802. circuit_dump_conn_details(severity, circ, conn->conn_array_index,
  803. "Exit-ward", n_circ_id, p_circ_id);
  804. }
  805. }
  806. }
  807. }
  808. }
  809. /** A helper function for circuit_dump_by_chan() below. Log a bunch
  810. * of information about circuit <b>circ</b>.
  811. */
  812. static void
  813. circuit_dump_chan_details(int severity,
  814. circuit_t *circ,
  815. channel_t *chan,
  816. const char *type,
  817. circid_t this_circid,
  818. circid_t other_circid)
  819. {
  820. tor_log(severity, LD_CIRC, "Conn %p has %s circuit: circID %u "
  821. "(other side %u), state %d (%s), born %ld:",
  822. chan, type, (unsigned)this_circid, (unsigned)other_circid, circ->state,
  823. circuit_state_to_string(circ->state),
  824. (long)circ->timestamp_began.tv_sec);
  825. if (CIRCUIT_IS_ORIGIN(circ)) { /* circ starts at this node */
  826. circuit_log_path(severity, LD_CIRC, TO_ORIGIN_CIRCUIT(circ));
  827. }
  828. }
  829. /** Log, at severity <b>severity</b>, information about each circuit
  830. * that is connected to <b>chan</b>.
  831. */
  832. void
  833. circuit_dump_by_chan(channel_t *chan, int severity)
  834. {
  835. circuit_t *circ;
  836. tor_assert(chan);
  837. TOR_LIST_FOREACH(circ, &global_circuitlist, head) {
  838. circid_t n_circ_id = circ->n_circ_id, p_circ_id = 0;
  839. if (circ->marked_for_close) {
  840. continue;
  841. }
  842. if (!CIRCUIT_IS_ORIGIN(circ)) {
  843. p_circ_id = TO_OR_CIRCUIT(circ)->p_circ_id;
  844. }
  845. if (! CIRCUIT_IS_ORIGIN(circ) && TO_OR_CIRCUIT(circ)->p_chan &&
  846. TO_OR_CIRCUIT(circ)->p_chan == chan) {
  847. circuit_dump_chan_details(severity, circ, chan, "App-ward",
  848. p_circ_id, n_circ_id);
  849. }
  850. if (circ->n_chan && circ->n_chan == chan) {
  851. circuit_dump_chan_details(severity, circ, chan, "Exit-ward",
  852. n_circ_id, p_circ_id);
  853. }
  854. if (!circ->n_chan && circ->n_hop &&
  855. channel_matches_extend_info(chan, circ->n_hop) &&
  856. tor_memeq(chan->identity_digest,
  857. circ->n_hop->identity_digest, DIGEST_LEN)) {
  858. circuit_dump_chan_details(severity, circ, chan,
  859. (circ->state == CIRCUIT_STATE_OPEN &&
  860. !CIRCUIT_IS_ORIGIN(circ)) ?
  861. "Endpoint" : "Pending",
  862. n_circ_id, p_circ_id);
  863. }
  864. }
  865. }
  866. /** Return the circuit whose global ID is <b>id</b>, or NULL if no
  867. * such circuit exists. */
  868. origin_circuit_t *
  869. circuit_get_by_global_id(uint32_t id)
  870. {
  871. circuit_t *circ;
  872. TOR_LIST_FOREACH(circ, &global_circuitlist, head) {
  873. if (CIRCUIT_IS_ORIGIN(circ) &&
  874. TO_ORIGIN_CIRCUIT(circ)->global_identifier == id) {
  875. if (circ->marked_for_close)
  876. return NULL;
  877. else
  878. return TO_ORIGIN_CIRCUIT(circ);
  879. }
  880. }
  881. return NULL;
  882. }
  883. /** Return a circ such that:
  884. * - circ-\>n_circ_id or circ-\>p_circ_id is equal to <b>circ_id</b>, and
  885. * - circ is attached to <b>chan</b>, either as p_chan or n_chan.
  886. * Return NULL if no such circuit exists.
  887. *
  888. * If <b>found_entry_out</b> is provided, set it to true if we have a
  889. * placeholder entry for circid/chan, and leave it unset otherwise.
  890. */
  891. static INLINE circuit_t *
  892. circuit_get_by_circid_channel_impl(circid_t circ_id, channel_t *chan,
  893. int *found_entry_out)
  894. {
  895. chan_circid_circuit_map_t search;
  896. chan_circid_circuit_map_t *found;
  897. if (_last_circid_chan_ent &&
  898. circ_id == _last_circid_chan_ent->circ_id &&
  899. chan == _last_circid_chan_ent->chan) {
  900. found = _last_circid_chan_ent;
  901. } else {
  902. search.circ_id = circ_id;
  903. search.chan = chan;
  904. found = HT_FIND(chan_circid_map, &chan_circid_map, &search);
  905. _last_circid_chan_ent = found;
  906. }
  907. if (found && found->circuit) {
  908. log_debug(LD_CIRC,
  909. "circuit_get_by_circid_channel_impl() returning circuit %p for"
  910. " circ_id %u, channel ID " U64_FORMAT " (%p)",
  911. found->circuit, (unsigned)circ_id,
  912. U64_PRINTF_ARG(chan->global_identifier), chan);
  913. if (found_entry_out)
  914. *found_entry_out = 1;
  915. return found->circuit;
  916. }
  917. log_debug(LD_CIRC,
  918. "circuit_get_by_circid_channel_impl() found %s for"
  919. " circ_id %u, channel ID " U64_FORMAT " (%p)",
  920. found ? "placeholder" : "nothing",
  921. (unsigned)circ_id,
  922. U64_PRINTF_ARG(chan->global_identifier), chan);
  923. if (found_entry_out)
  924. *found_entry_out = found ? 1 : 0;
  925. return NULL;
  926. /* The rest of this checks for bugs. Disabled by default. */
  927. /* We comment it out because coverity complains otherwise.
  928. {
  929. circuit_t *circ;
  930. TOR_LIST_FOREACH(circ, &global_circuitlist, head) {
  931. if (! CIRCUIT_IS_ORIGIN(circ)) {
  932. or_circuit_t *or_circ = TO_OR_CIRCUIT(circ);
  933. if (or_circ->p_chan == chan && or_circ->p_circ_id == circ_id) {
  934. log_warn(LD_BUG,
  935. "circuit matches p_chan, but not in hash table (Bug!)");
  936. return circ;
  937. }
  938. }
  939. if (circ->n_chan == chan && circ->n_circ_id == circ_id) {
  940. log_warn(LD_BUG,
  941. "circuit matches n_chan, but not in hash table (Bug!)");
  942. return circ;
  943. }
  944. }
  945. return NULL;
  946. } */
  947. }
  948. /** Return a circ such that:
  949. * - circ-\>n_circ_id or circ-\>p_circ_id is equal to <b>circ_id</b>, and
  950. * - circ is attached to <b>chan</b>, either as p_chan or n_chan.
  951. * - circ is not marked for close.
  952. * Return NULL if no such circuit exists.
  953. */
  954. circuit_t *
  955. circuit_get_by_circid_channel(circid_t circ_id, channel_t *chan)
  956. {
  957. circuit_t *circ = circuit_get_by_circid_channel_impl(circ_id, chan, NULL);
  958. if (!circ || circ->marked_for_close)
  959. return NULL;
  960. else
  961. return circ;
  962. }
  963. /** Return a circ such that:
  964. * - circ-\>n_circ_id or circ-\>p_circ_id is equal to <b>circ_id</b>, and
  965. * - circ is attached to <b>chan</b>, either as p_chan or n_chan.
  966. * Return NULL if no such circuit exists.
  967. */
  968. circuit_t *
  969. circuit_get_by_circid_channel_even_if_marked(circid_t circ_id,
  970. channel_t *chan)
  971. {
  972. return circuit_get_by_circid_channel_impl(circ_id, chan, NULL);
  973. }
  974. /** Return true iff the circuit ID <b>circ_id</b> is currently used by a
  975. * circuit, marked or not, on <b>chan</b>. */
  976. int
  977. circuit_id_in_use_on_channel(circid_t circ_id, channel_t *chan)
  978. {
  979. int found = 0;
  980. return circuit_get_by_circid_channel_impl(circ_id, chan, &found) != NULL
  981. || found;
  982. }
  983. /** Return the circuit that a given edge connection is using. */
  984. circuit_t *
  985. circuit_get_by_edge_conn(edge_connection_t *conn)
  986. {
  987. circuit_t *circ;
  988. circ = conn->on_circuit;
  989. tor_assert(!circ ||
  990. (CIRCUIT_IS_ORIGIN(circ) ? circ->magic == ORIGIN_CIRCUIT_MAGIC
  991. : circ->magic == OR_CIRCUIT_MAGIC));
  992. return circ;
  993. }
  994. /** For each circuit that has <b>chan</b> as n_chan or p_chan, unlink the
  995. * circuit from the chan,circid map, and mark it for close if it hasn't
  996. * been marked already.
  997. */
  998. void
  999. circuit_unlink_all_from_channel(channel_t *chan, int reason)
  1000. {
  1001. circuit_t *circ;
  1002. channel_unlink_all_circuits(chan);
  1003. TOR_LIST_FOREACH(circ, &global_circuitlist, head) {
  1004. int mark = 0;
  1005. if (circ->n_chan == chan) {
  1006. circuit_set_n_circid_chan(circ, 0, NULL);
  1007. mark = 1;
  1008. /* If we didn't request this closure, pass the remote
  1009. * bit to mark_for_close. */
  1010. if (chan->reason_for_closing != CHANNEL_CLOSE_REQUESTED)
  1011. reason |= END_CIRC_REASON_FLAG_REMOTE;
  1012. }
  1013. if (! CIRCUIT_IS_ORIGIN(circ)) {
  1014. or_circuit_t *or_circ = TO_OR_CIRCUIT(circ);
  1015. if (or_circ->p_chan == chan) {
  1016. circuit_set_p_circid_chan(or_circ, 0, NULL);
  1017. mark = 1;
  1018. }
  1019. }
  1020. if (mark && !circ->marked_for_close)
  1021. circuit_mark_for_close(circ, reason);
  1022. }
  1023. }
  1024. /** Return a circ such that
  1025. * - circ-\>rend_data-\>onion_address is equal to
  1026. * <b>rend_data</b>-\>onion_address,
  1027. * - circ-\>rend_data-\>rend_cookie is equal to
  1028. * <b>rend_data</b>-\>rend_cookie, and
  1029. * - circ-\>purpose is equal to CIRCUIT_PURPOSE_C_REND_READY.
  1030. *
  1031. * Return NULL if no such circuit exists.
  1032. */
  1033. origin_circuit_t *
  1034. circuit_get_ready_rend_circ_by_rend_data(const rend_data_t *rend_data)
  1035. {
  1036. circuit_t *circ;
  1037. TOR_LIST_FOREACH(circ, &global_circuitlist, head) {
  1038. if (!circ->marked_for_close &&
  1039. circ->purpose == CIRCUIT_PURPOSE_C_REND_READY) {
  1040. origin_circuit_t *ocirc = TO_ORIGIN_CIRCUIT(circ);
  1041. if (ocirc->rend_data &&
  1042. !rend_cmp_service_ids(rend_data->onion_address,
  1043. ocirc->rend_data->onion_address) &&
  1044. tor_memeq(ocirc->rend_data->rend_cookie,
  1045. rend_data->rend_cookie,
  1046. REND_COOKIE_LEN))
  1047. return ocirc;
  1048. }
  1049. }
  1050. return NULL;
  1051. }
  1052. /** Return the first circuit originating here in global_circuitlist after
  1053. * <b>start</b> whose purpose is <b>purpose</b>, and where
  1054. * <b>digest</b> (if set) matches the rend_pk_digest field. Return NULL if no
  1055. * circuit is found. If <b>start</b> is NULL, begin at the start of the list.
  1056. */
  1057. origin_circuit_t *
  1058. circuit_get_next_by_pk_and_purpose(origin_circuit_t *start,
  1059. const char *digest, uint8_t purpose)
  1060. {
  1061. circuit_t *circ;
  1062. tor_assert(CIRCUIT_PURPOSE_IS_ORIGIN(purpose));
  1063. if (start == NULL)
  1064. circ = TOR_LIST_FIRST(&global_circuitlist);
  1065. else
  1066. circ = TOR_LIST_NEXT(TO_CIRCUIT(start), head);
  1067. for ( ; circ; circ = TOR_LIST_NEXT(circ, head)) {
  1068. if (circ->marked_for_close)
  1069. continue;
  1070. if (circ->purpose != purpose)
  1071. continue;
  1072. if (!digest)
  1073. return TO_ORIGIN_CIRCUIT(circ);
  1074. else if (TO_ORIGIN_CIRCUIT(circ)->rend_data &&
  1075. tor_memeq(TO_ORIGIN_CIRCUIT(circ)->rend_data->rend_pk_digest,
  1076. digest, DIGEST_LEN))
  1077. return TO_ORIGIN_CIRCUIT(circ);
  1078. }
  1079. return NULL;
  1080. }
  1081. /** Return the first OR circuit in the global list whose purpose is
  1082. * <b>purpose</b>, and whose rend_token is the <b>len</b>-byte
  1083. * <b>token</b>. */
  1084. static or_circuit_t *
  1085. circuit_get_by_rend_token_and_purpose(uint8_t purpose, const char *token,
  1086. size_t len)
  1087. {
  1088. circuit_t *circ;
  1089. TOR_LIST_FOREACH(circ, &global_circuitlist, head) {
  1090. if (! circ->marked_for_close &&
  1091. circ->purpose == purpose &&
  1092. tor_memeq(TO_OR_CIRCUIT(circ)->rend_token, token, len))
  1093. return TO_OR_CIRCUIT(circ);
  1094. }
  1095. return NULL;
  1096. }
  1097. /** Return the circuit waiting for a rendezvous with the provided cookie.
  1098. * Return NULL if no such circuit is found.
  1099. */
  1100. or_circuit_t *
  1101. circuit_get_rendezvous(const char *cookie)
  1102. {
  1103. return circuit_get_by_rend_token_and_purpose(
  1104. CIRCUIT_PURPOSE_REND_POINT_WAITING,
  1105. cookie, REND_COOKIE_LEN);
  1106. }
  1107. /** Return the circuit waiting for intro cells of the given digest.
  1108. * Return NULL if no such circuit is found.
  1109. */
  1110. or_circuit_t *
  1111. circuit_get_intro_point(const char *digest)
  1112. {
  1113. return circuit_get_by_rend_token_and_purpose(
  1114. CIRCUIT_PURPOSE_INTRO_POINT, digest,
  1115. DIGEST_LEN);
  1116. }
  1117. /** Return a circuit that is open, is CIRCUIT_PURPOSE_C_GENERAL,
  1118. * has a timestamp_dirty value of 0, has flags matching the CIRCLAUNCH_*
  1119. * flags in <b>flags</b>, and if info is defined, does not already use info
  1120. * as any of its hops; or NULL if no circuit fits this description.
  1121. *
  1122. * The <b>purpose</b> argument (currently ignored) refers to the purpose of
  1123. * the circuit we want to create, not the purpose of the circuit we want to
  1124. * cannibalize.
  1125. *
  1126. * If !CIRCLAUNCH_NEED_UPTIME, prefer returning non-uptime circuits.
  1127. */
  1128. origin_circuit_t *
  1129. circuit_find_to_cannibalize(uint8_t purpose, extend_info_t *info,
  1130. int flags)
  1131. {
  1132. circuit_t *circ_;
  1133. origin_circuit_t *best=NULL;
  1134. int need_uptime = (flags & CIRCLAUNCH_NEED_UPTIME) != 0;
  1135. int need_capacity = (flags & CIRCLAUNCH_NEED_CAPACITY) != 0;
  1136. int internal = (flags & CIRCLAUNCH_IS_INTERNAL) != 0;
  1137. const or_options_t *options = get_options();
  1138. /* Make sure we're not trying to create a onehop circ by
  1139. * cannibalization. */
  1140. tor_assert(!(flags & CIRCLAUNCH_ONEHOP_TUNNEL));
  1141. log_debug(LD_CIRC,
  1142. "Hunting for a circ to cannibalize: purpose %d, uptime %d, "
  1143. "capacity %d, internal %d",
  1144. purpose, need_uptime, need_capacity, internal);
  1145. TOR_LIST_FOREACH(circ_, &global_circuitlist, head) {
  1146. if (CIRCUIT_IS_ORIGIN(circ_) &&
  1147. circ_->state == CIRCUIT_STATE_OPEN &&
  1148. !circ_->marked_for_close &&
  1149. circ_->purpose == CIRCUIT_PURPOSE_C_GENERAL &&
  1150. !circ_->timestamp_dirty) {
  1151. origin_circuit_t *circ = TO_ORIGIN_CIRCUIT(circ_);
  1152. if ((!need_uptime || circ->build_state->need_uptime) &&
  1153. (!need_capacity || circ->build_state->need_capacity) &&
  1154. (internal == circ->build_state->is_internal) &&
  1155. !circ->unusable_for_new_conns &&
  1156. circ->remaining_relay_early_cells &&
  1157. circ->build_state->desired_path_len == DEFAULT_ROUTE_LEN &&
  1158. !circ->build_state->onehop_tunnel &&
  1159. !circ->isolation_values_set) {
  1160. if (info) {
  1161. /* need to make sure we don't duplicate hops */
  1162. crypt_path_t *hop = circ->cpath;
  1163. const node_t *ri1 = node_get_by_id(info->identity_digest);
  1164. do {
  1165. const node_t *ri2;
  1166. if (tor_memeq(hop->extend_info->identity_digest,
  1167. info->identity_digest, DIGEST_LEN))
  1168. goto next;
  1169. if (ri1 &&
  1170. (ri2 = node_get_by_id(hop->extend_info->identity_digest))
  1171. && nodes_in_same_family(ri1, ri2))
  1172. goto next;
  1173. hop=hop->next;
  1174. } while (hop!=circ->cpath);
  1175. }
  1176. if (options->ExcludeNodes) {
  1177. /* Make sure no existing nodes in the circuit are excluded for
  1178. * general use. (This may be possible if StrictNodes is 0, and we
  1179. * thought we needed to use an otherwise excluded node for, say, a
  1180. * directory operation.) */
  1181. crypt_path_t *hop = circ->cpath;
  1182. do {
  1183. if (routerset_contains_extendinfo(options->ExcludeNodes,
  1184. hop->extend_info))
  1185. goto next;
  1186. hop = hop->next;
  1187. } while (hop != circ->cpath);
  1188. }
  1189. if (!best || (best->build_state->need_uptime && !need_uptime))
  1190. best = circ;
  1191. next: ;
  1192. }
  1193. }
  1194. }
  1195. return best;
  1196. }
  1197. /** Return the number of hops in circuit's path. */
  1198. int
  1199. circuit_get_cpath_len(origin_circuit_t *circ)
  1200. {
  1201. int n = 0;
  1202. if (circ && circ->cpath) {
  1203. crypt_path_t *cpath, *cpath_next = NULL;
  1204. for (cpath = circ->cpath; cpath_next != circ->cpath; cpath = cpath_next) {
  1205. cpath_next = cpath->next;
  1206. ++n;
  1207. }
  1208. }
  1209. return n;
  1210. }
  1211. /** Return the <b>hopnum</b>th hop in <b>circ</b>->cpath, or NULL if there
  1212. * aren't that many hops in the list. */
  1213. crypt_path_t *
  1214. circuit_get_cpath_hop(origin_circuit_t *circ, int hopnum)
  1215. {
  1216. if (circ && circ->cpath && hopnum > 0) {
  1217. crypt_path_t *cpath, *cpath_next = NULL;
  1218. for (cpath = circ->cpath; cpath_next != circ->cpath; cpath = cpath_next) {
  1219. cpath_next = cpath->next;
  1220. if (--hopnum <= 0)
  1221. return cpath;
  1222. }
  1223. }
  1224. return NULL;
  1225. }
  1226. /** Go through the circuitlist; mark-for-close each circuit that starts
  1227. * at us but has not yet been used. */
  1228. void
  1229. circuit_mark_all_unused_circs(void)
  1230. {
  1231. circuit_t *circ;
  1232. TOR_LIST_FOREACH(circ, &global_circuitlist, head) {
  1233. if (CIRCUIT_IS_ORIGIN(circ) &&
  1234. !circ->marked_for_close &&
  1235. !circ->timestamp_dirty)
  1236. circuit_mark_for_close(circ, END_CIRC_REASON_FINISHED);
  1237. }
  1238. }
  1239. /** Go through the circuitlist; for each circuit that starts at us
  1240. * and is dirty, frob its timestamp_dirty so we won't use it for any
  1241. * new streams.
  1242. *
  1243. * This is useful for letting the user change pseudonyms, so new
  1244. * streams will not be linkable to old streams.
  1245. */
  1246. void
  1247. circuit_mark_all_dirty_circs_as_unusable(void)
  1248. {
  1249. circuit_t *circ;
  1250. TOR_LIST_FOREACH(circ, &global_circuitlist, head) {
  1251. if (CIRCUIT_IS_ORIGIN(circ) &&
  1252. !circ->marked_for_close &&
  1253. circ->timestamp_dirty) {
  1254. mark_circuit_unusable_for_new_conns(TO_ORIGIN_CIRCUIT(circ));
  1255. }
  1256. }
  1257. }
  1258. /** Mark <b>circ</b> to be closed next time we call
  1259. * circuit_close_all_marked(). Do any cleanup needed:
  1260. * - If state is onionskin_pending, remove circ from the onion_pending
  1261. * list.
  1262. * - If circ isn't open yet: call circuit_build_failed() if we're
  1263. * the origin, and in either case call circuit_rep_hist_note_result()
  1264. * to note stats.
  1265. * - If purpose is C_INTRODUCE_ACK_WAIT, report the intro point
  1266. * failure we just had to the hidden service client module.
  1267. * - If purpose is C_INTRODUCING and <b>reason</b> isn't TIMEOUT,
  1268. * report to the hidden service client module that the intro point
  1269. * we just tried may be unreachable.
  1270. * - Send appropriate destroys and edge_destroys for conns and
  1271. * streams attached to circ.
  1272. * - If circ->rend_splice is set (we are the midpoint of a joined
  1273. * rendezvous stream), then mark the other circuit to close as well.
  1274. */
  1275. void
  1276. circuit_mark_for_close_(circuit_t *circ, int reason, int line,
  1277. const char *file)
  1278. {
  1279. int orig_reason = reason; /* Passed to the controller */
  1280. assert_circuit_ok(circ);
  1281. tor_assert(line);
  1282. tor_assert(file);
  1283. if (circ->marked_for_close) {
  1284. log_warn(LD_BUG,
  1285. "Duplicate call to circuit_mark_for_close at %s:%d"
  1286. " (first at %s:%d)", file, line,
  1287. circ->marked_for_close_file, circ->marked_for_close);
  1288. return;
  1289. }
  1290. if (reason == END_CIRC_AT_ORIGIN) {
  1291. if (!CIRCUIT_IS_ORIGIN(circ)) {
  1292. log_warn(LD_BUG, "Specified 'at-origin' non-reason for ending circuit, "
  1293. "but circuit was not at origin. (called %s:%d, purpose=%d)",
  1294. file, line, circ->purpose);
  1295. }
  1296. reason = END_CIRC_REASON_NONE;
  1297. }
  1298. if (CIRCUIT_IS_ORIGIN(circ)) {
  1299. if (pathbias_check_close(TO_ORIGIN_CIRCUIT(circ), reason) == -1) {
  1300. /* Don't close it yet, we need to test it first */
  1301. return;
  1302. }
  1303. /* We don't send reasons when closing circuits at the origin. */
  1304. reason = END_CIRC_REASON_NONE;
  1305. }
  1306. if (reason & END_CIRC_REASON_FLAG_REMOTE)
  1307. reason &= ~END_CIRC_REASON_FLAG_REMOTE;
  1308. if (reason < END_CIRC_REASON_MIN_ || reason > END_CIRC_REASON_MAX_) {
  1309. if (!(orig_reason & END_CIRC_REASON_FLAG_REMOTE))
  1310. log_warn(LD_BUG, "Reason %d out of range at %s:%d", reason, file, line);
  1311. reason = END_CIRC_REASON_NONE;
  1312. }
  1313. if (circ->state == CIRCUIT_STATE_ONIONSKIN_PENDING) {
  1314. onion_pending_remove(TO_OR_CIRCUIT(circ));
  1315. }
  1316. /* If the circuit ever became OPEN, we sent it to the reputation history
  1317. * module then. If it isn't OPEN, we send it there now to remember which
  1318. * links worked and which didn't.
  1319. */
  1320. if (circ->state != CIRCUIT_STATE_OPEN) {
  1321. if (CIRCUIT_IS_ORIGIN(circ)) {
  1322. origin_circuit_t *ocirc = TO_ORIGIN_CIRCUIT(circ);
  1323. circuit_build_failed(ocirc); /* take actions if necessary */
  1324. circuit_rep_hist_note_result(ocirc);
  1325. }
  1326. }
  1327. if (circ->state == CIRCUIT_STATE_CHAN_WAIT) {
  1328. if (circuits_pending_chans)
  1329. smartlist_remove(circuits_pending_chans, circ);
  1330. }
  1331. if (CIRCUIT_IS_ORIGIN(circ)) {
  1332. control_event_circuit_status(TO_ORIGIN_CIRCUIT(circ),
  1333. (circ->state == CIRCUIT_STATE_OPEN)?CIRC_EVENT_CLOSED:CIRC_EVENT_FAILED,
  1334. orig_reason);
  1335. }
  1336. if (circ->purpose == CIRCUIT_PURPOSE_C_INTRODUCE_ACK_WAIT) {
  1337. origin_circuit_t *ocirc = TO_ORIGIN_CIRCUIT(circ);
  1338. int timed_out = (reason == END_CIRC_REASON_TIMEOUT);
  1339. tor_assert(circ->state == CIRCUIT_STATE_OPEN);
  1340. tor_assert(ocirc->build_state->chosen_exit);
  1341. tor_assert(ocirc->rend_data);
  1342. /* treat this like getting a nack from it */
  1343. log_info(LD_REND, "Failed intro circ %s to %s (awaiting ack). %s",
  1344. safe_str_client(ocirc->rend_data->onion_address),
  1345. safe_str_client(build_state_get_exit_nickname(ocirc->build_state)),
  1346. timed_out ? "Recording timeout." : "Removing from descriptor.");
  1347. rend_client_report_intro_point_failure(ocirc->build_state->chosen_exit,
  1348. ocirc->rend_data,
  1349. timed_out ?
  1350. INTRO_POINT_FAILURE_TIMEOUT :
  1351. INTRO_POINT_FAILURE_GENERIC);
  1352. } else if (circ->purpose == CIRCUIT_PURPOSE_C_INTRODUCING &&
  1353. reason != END_CIRC_REASON_TIMEOUT) {
  1354. origin_circuit_t *ocirc = TO_ORIGIN_CIRCUIT(circ);
  1355. if (ocirc->build_state->chosen_exit && ocirc->rend_data) {
  1356. log_info(LD_REND, "Failed intro circ %s to %s "
  1357. "(building circuit to intro point). "
  1358. "Marking intro point as possibly unreachable.",
  1359. safe_str_client(ocirc->rend_data->onion_address),
  1360. safe_str_client(build_state_get_exit_nickname(ocirc->build_state)));
  1361. rend_client_report_intro_point_failure(ocirc->build_state->chosen_exit,
  1362. ocirc->rend_data,
  1363. INTRO_POINT_FAILURE_UNREACHABLE);
  1364. }
  1365. }
  1366. if (circ->n_chan) {
  1367. circuit_clear_cell_queue(circ, circ->n_chan);
  1368. /* Only send destroy if the channel isn't closing anyway */
  1369. if (!(circ->n_chan->state == CHANNEL_STATE_CLOSING ||
  1370. circ->n_chan->state == CHANNEL_STATE_CLOSED ||
  1371. circ->n_chan->state == CHANNEL_STATE_ERROR)) {
  1372. channel_send_destroy(circ->n_circ_id, circ->n_chan, reason);
  1373. }
  1374. circuitmux_detach_circuit(circ->n_chan->cmux, circ);
  1375. }
  1376. if (! CIRCUIT_IS_ORIGIN(circ)) {
  1377. or_circuit_t *or_circ = TO_OR_CIRCUIT(circ);
  1378. edge_connection_t *conn;
  1379. for (conn=or_circ->n_streams; conn; conn=conn->next_stream)
  1380. connection_edge_destroy(or_circ->p_circ_id, conn);
  1381. or_circ->n_streams = NULL;
  1382. while (or_circ->resolving_streams) {
  1383. conn = or_circ->resolving_streams;
  1384. or_circ->resolving_streams = conn->next_stream;
  1385. if (!conn->base_.marked_for_close) {
  1386. /* The client will see a DESTROY, and infer that the connections
  1387. * are closing because the circuit is getting torn down. No need
  1388. * to send an end cell. */
  1389. conn->edge_has_sent_end = 1;
  1390. conn->end_reason = END_STREAM_REASON_DESTROY;
  1391. conn->end_reason |= END_STREAM_REASON_FLAG_ALREADY_SENT_CLOSED;
  1392. connection_mark_for_close(TO_CONN(conn));
  1393. }
  1394. conn->on_circuit = NULL;
  1395. }
  1396. if (or_circ->p_chan) {
  1397. circuit_clear_cell_queue(circ, or_circ->p_chan);
  1398. /* Only send destroy if the channel isn't closing anyway */
  1399. if (!(or_circ->p_chan->state == CHANNEL_STATE_CLOSING ||
  1400. or_circ->p_chan->state == CHANNEL_STATE_CLOSED ||
  1401. or_circ->p_chan->state == CHANNEL_STATE_ERROR)) {
  1402. channel_send_destroy(or_circ->p_circ_id, or_circ->p_chan, reason);
  1403. }
  1404. circuitmux_detach_circuit(or_circ->p_chan->cmux, circ);
  1405. }
  1406. } else {
  1407. origin_circuit_t *ocirc = TO_ORIGIN_CIRCUIT(circ);
  1408. edge_connection_t *conn;
  1409. for (conn=ocirc->p_streams; conn; conn=conn->next_stream)
  1410. connection_edge_destroy(circ->n_circ_id, conn);
  1411. ocirc->p_streams = NULL;
  1412. }
  1413. circ->marked_for_close = line;
  1414. circ->marked_for_close_file = file;
  1415. if (!CIRCUIT_IS_ORIGIN(circ)) {
  1416. or_circuit_t *or_circ = TO_OR_CIRCUIT(circ);
  1417. if (or_circ->rend_splice) {
  1418. if (!or_circ->rend_splice->base_.marked_for_close) {
  1419. /* do this after marking this circuit, to avoid infinite recursion. */
  1420. circuit_mark_for_close(TO_CIRCUIT(or_circ->rend_splice), reason);
  1421. }
  1422. or_circ->rend_splice = NULL;
  1423. }
  1424. }
  1425. }
  1426. /** Given a marked circuit <b>circ</b>, aggressively free its cell queues to
  1427. * recover memory. */
  1428. static void
  1429. marked_circuit_free_cells(circuit_t *circ)
  1430. {
  1431. if (!circ->marked_for_close) {
  1432. log_warn(LD_BUG, "Called on non-marked circuit");
  1433. return;
  1434. }
  1435. cell_queue_clear(&circ->n_chan_cells);
  1436. if (! CIRCUIT_IS_ORIGIN(circ))
  1437. cell_queue_clear(& TO_OR_CIRCUIT(circ)->p_chan_cells);
  1438. }
  1439. /** Return the number of cells used by the circuit <b>c</b>'s cell queues. */
  1440. STATIC size_t
  1441. n_cells_in_circ_queues(const circuit_t *c)
  1442. {
  1443. size_t n = c->n_chan_cells.n;
  1444. if (! CIRCUIT_IS_ORIGIN(c)) {
  1445. circuit_t *cc = (circuit_t *) c;
  1446. n += TO_OR_CIRCUIT(cc)->p_chan_cells.n;
  1447. }
  1448. return n;
  1449. }
  1450. /** helper to sort a list of circuit_q by total queue lengths, in descending
  1451. * order. */
  1452. static int
  1453. circuits_compare_by_queue_len_(const void **a_, const void **b_)
  1454. {
  1455. const circuit_t *a = *a_;
  1456. const circuit_t *b = *b_;
  1457. size_t a_n = n_cells_in_circ_queues(a);
  1458. size_t b_n = n_cells_in_circ_queues(b);
  1459. if (a_n < b_n)
  1460. return 1;
  1461. else if (a_n == b_n)
  1462. return 0;
  1463. else
  1464. return -1;
  1465. }
  1466. #define FRACTION_OF_CIRCS_TO_RETAIN_ON_OOM 0.90
  1467. /** We're out of memory for cells, having allocated <b>current_allocation</b>
  1468. * bytes' worth. Kill the 'worst' circuits until we're under
  1469. * FRACTION_OF_CIRCS_TO_RETAIN_ON_OOM of our maximum usage. */
  1470. void
  1471. circuits_handle_oom(size_t current_allocation)
  1472. {
  1473. /* Let's hope there's enough slack space for this allocation here... */
  1474. smartlist_t *circlist = smartlist_new();
  1475. circuit_t *circ;
  1476. size_t n_cells_removed=0, n_cells_to_remove;
  1477. int n_circuits_killed=0;
  1478. log_notice(LD_GENERAL, "We're low on memory. Killing circuits with "
  1479. "over-long queues. (This behavior is controlled by "
  1480. "MaxMemInCellQueues.)");
  1481. {
  1482. size_t mem_target = (size_t)(get_options()->MaxMemInCellQueues *
  1483. FRACTION_OF_CIRCS_TO_RETAIN_ON_OOM);
  1484. size_t mem_to_recover;
  1485. if (current_allocation <= mem_target)
  1486. return;
  1487. mem_to_recover = current_allocation - mem_target;
  1488. n_cells_to_remove = CEIL_DIV(mem_to_recover, packed_cell_mem_cost());
  1489. }
  1490. /* This algorithm itself assumes that you've got enough memory slack
  1491. * to actually run it. */
  1492. TOR_LIST_FOREACH(circ, &global_circuitlist, head)
  1493. smartlist_add(circlist, circ);
  1494. /* This is O(n log n); there are faster algorithms we could use instead.
  1495. * Let's hope this doesn't happen enough to be in the critical path. */
  1496. smartlist_sort(circlist, circuits_compare_by_queue_len_);
  1497. /* Okay, now the worst circuits are at the front of the list. Let's mark
  1498. * them, and reclaim their storage aggressively. */
  1499. SMARTLIST_FOREACH_BEGIN(circlist, circuit_t *, circ) {
  1500. size_t n = n_cells_in_circ_queues(circ);
  1501. if (! circ->marked_for_close) {
  1502. circuit_mark_for_close(circ, END_CIRC_REASON_RESOURCELIMIT);
  1503. }
  1504. marked_circuit_free_cells(circ);
  1505. ++n_circuits_killed;
  1506. n_cells_removed += n;
  1507. if (n_cells_removed >= n_cells_to_remove)
  1508. break;
  1509. } SMARTLIST_FOREACH_END(circ);
  1510. clean_cell_pool(); /* In case this helps. */
  1511. log_notice(LD_GENERAL, "Removed "U64_FORMAT" bytes by killing %d circuits.",
  1512. U64_PRINTF_ARG(n_cells_removed * packed_cell_mem_cost()),
  1513. n_circuits_killed);
  1514. smartlist_free(circlist);
  1515. }
  1516. /** Verify that cpath layer <b>cp</b> has all of its invariants
  1517. * correct. Trigger an assert if anything is invalid.
  1518. */
  1519. void
  1520. assert_cpath_layer_ok(const crypt_path_t *cp)
  1521. {
  1522. // tor_assert(cp->addr); /* these are zero for rendezvous extra-hops */
  1523. // tor_assert(cp->port);
  1524. tor_assert(cp);
  1525. tor_assert(cp->magic == CRYPT_PATH_MAGIC);
  1526. switch (cp->state)
  1527. {
  1528. case CPATH_STATE_OPEN:
  1529. tor_assert(cp->f_crypto);
  1530. tor_assert(cp->b_crypto);
  1531. /* fall through */
  1532. case CPATH_STATE_CLOSED:
  1533. /*XXXX Assert that there's no handshake_state either. */
  1534. tor_assert(!cp->rend_dh_handshake_state);
  1535. break;
  1536. case CPATH_STATE_AWAITING_KEYS:
  1537. /* tor_assert(cp->dh_handshake_state); */
  1538. break;
  1539. default:
  1540. log_fn(LOG_ERR, LD_BUG, "Unexpected state %d", cp->state);
  1541. tor_assert(0);
  1542. }
  1543. tor_assert(cp->package_window >= 0);
  1544. tor_assert(cp->deliver_window >= 0);
  1545. }
  1546. /** Verify that cpath <b>cp</b> has all of its invariants
  1547. * correct. Trigger an assert if anything is invalid.
  1548. */
  1549. static void
  1550. assert_cpath_ok(const crypt_path_t *cp)
  1551. {
  1552. const crypt_path_t *start = cp;
  1553. do {
  1554. assert_cpath_layer_ok(cp);
  1555. /* layers must be in sequence of: "open* awaiting? closed*" */
  1556. if (cp != start) {
  1557. if (cp->state == CPATH_STATE_AWAITING_KEYS) {
  1558. tor_assert(cp->prev->state == CPATH_STATE_OPEN);
  1559. } else if (cp->state == CPATH_STATE_OPEN) {
  1560. tor_assert(cp->prev->state == CPATH_STATE_OPEN);
  1561. }
  1562. }
  1563. cp = cp->next;
  1564. tor_assert(cp);
  1565. } while (cp != start);
  1566. }
  1567. /** Verify that circuit <b>c</b> has all of its invariants
  1568. * correct. Trigger an assert if anything is invalid.
  1569. */
  1570. void
  1571. assert_circuit_ok(const circuit_t *c)
  1572. {
  1573. edge_connection_t *conn;
  1574. const or_circuit_t *or_circ = NULL;
  1575. const origin_circuit_t *origin_circ = NULL;
  1576. tor_assert(c);
  1577. tor_assert(c->magic == ORIGIN_CIRCUIT_MAGIC || c->magic == OR_CIRCUIT_MAGIC);
  1578. tor_assert(c->purpose >= CIRCUIT_PURPOSE_MIN_ &&
  1579. c->purpose <= CIRCUIT_PURPOSE_MAX_);
  1580. {
  1581. /* Having a separate variable for this pleases GCC 4.2 in ways I hope I
  1582. * never understand. -NM. */
  1583. circuit_t *nonconst_circ = (circuit_t*) c;
  1584. if (CIRCUIT_IS_ORIGIN(c))
  1585. origin_circ = TO_ORIGIN_CIRCUIT(nonconst_circ);
  1586. else
  1587. or_circ = TO_OR_CIRCUIT(nonconst_circ);
  1588. }
  1589. if (c->n_chan) {
  1590. tor_assert(!c->n_hop);
  1591. if (c->n_circ_id) {
  1592. /* We use the _impl variant here to make sure we don't fail on marked
  1593. * circuits, which would not be returned by the regular function. */
  1594. circuit_t *c2 = circuit_get_by_circid_channel_impl(c->n_circ_id,
  1595. c->n_chan, NULL);
  1596. tor_assert(c == c2);
  1597. }
  1598. }
  1599. if (or_circ && or_circ->p_chan) {
  1600. if (or_circ->p_circ_id) {
  1601. /* ibid */
  1602. circuit_t *c2 =
  1603. circuit_get_by_circid_channel_impl(or_circ->p_circ_id,
  1604. or_circ->p_chan, NULL);
  1605. tor_assert(c == c2);
  1606. }
  1607. }
  1608. if (or_circ)
  1609. for (conn = or_circ->n_streams; conn; conn = conn->next_stream)
  1610. tor_assert(conn->base_.type == CONN_TYPE_EXIT);
  1611. tor_assert(c->deliver_window >= 0);
  1612. tor_assert(c->package_window >= 0);
  1613. if (c->state == CIRCUIT_STATE_OPEN) {
  1614. tor_assert(!c->n_chan_create_cell);
  1615. if (or_circ) {
  1616. tor_assert(or_circ->n_crypto);
  1617. tor_assert(or_circ->p_crypto);
  1618. tor_assert(or_circ->n_digest);
  1619. tor_assert(or_circ->p_digest);
  1620. }
  1621. }
  1622. if (c->state == CIRCUIT_STATE_CHAN_WAIT && !c->marked_for_close) {
  1623. tor_assert(circuits_pending_chans &&
  1624. smartlist_contains(circuits_pending_chans, c));
  1625. } else {
  1626. tor_assert(!circuits_pending_chans ||
  1627. !smartlist_contains(circuits_pending_chans, c));
  1628. }
  1629. if (origin_circ && origin_circ->cpath) {
  1630. assert_cpath_ok(origin_circ->cpath);
  1631. }
  1632. if (c->purpose == CIRCUIT_PURPOSE_REND_ESTABLISHED) {
  1633. tor_assert(or_circ);
  1634. if (!c->marked_for_close) {
  1635. tor_assert(or_circ->rend_splice);
  1636. tor_assert(or_circ->rend_splice->rend_splice == or_circ);
  1637. }
  1638. tor_assert(or_circ->rend_splice != or_circ);
  1639. } else {
  1640. tor_assert(!or_circ || !or_circ->rend_splice);
  1641. }
  1642. }