circuitlist.c 88 KB

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