circuitlist.c 89 KB

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