circuitlist.c 91 KB

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