circuitlist.c 87 KB

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