circuitlist.c 88 KB

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