circuitlist.c 92 KB

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