circuitlist.c 67 KB

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