circuitlist.c 87 KB

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