circuitlist.c 82 KB

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