circuitlist.c 94 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912
  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/mainloop/connection.h"
  65. #include "app/config/config.h"
  66. #include "core/or/connection_edge.h"
  67. #include "core/or/connection_or.h"
  68. #include "feature/control/control.h"
  69. #include "lib/crypt_ops/crypto_rand.h"
  70. #include "lib/crypt_ops/crypto_util.h"
  71. #include "lib/crypt_ops/crypto_dh.h"
  72. #include "feature/dircommon/directory.h"
  73. #include "feature/client/entrynodes.h"
  74. #include "core/mainloop/mainloop.h"
  75. #include "feature/hs/hs_circuit.h"
  76. #include "feature/hs/hs_circuitmap.h"
  77. #include "feature/hs/hs_ident.h"
  78. #include "feature/nodelist/networkstatus.h"
  79. #include "feature/nodelist/nodelist.h"
  80. #include "feature/relay/onion_queue.h"
  81. #include "core/crypto/onion_crypto.h"
  82. #include "core/crypto/onion_fast.h"
  83. #include "core/or/policies.h"
  84. #include "core/or/relay.h"
  85. #include "core/crypto/relay_crypto.h"
  86. #include "feature/rend/rendclient.h"
  87. #include "feature/rend/rendcommon.h"
  88. #include "feature/stats/predict_ports.h"
  89. #include "feature/stats/rephist.h"
  90. #include "feature/nodelist/routerlist.h"
  91. #include "feature/nodelist/routerset.h"
  92. #include "core/or/channelpadding.h"
  93. #include "lib/compress/compress.h"
  94. #include "lib/compress/compress_lzma.h"
  95. #include "lib/compress/compress_zlib.h"
  96. #include "lib/compress/compress_zstd.h"
  97. #include "lib/buf/buffers.h"
  98. #define OCIRC_EVENT_PRIVATE
  99. #include "core/or/ocirc_event.h"
  100. #include "ht.h"
  101. #include "core/or/cpath_build_state_st.h"
  102. #include "core/or/crypt_path_reference_st.h"
  103. #include "feature/dircommon/dir_connection_st.h"
  104. #include "core/or/edge_connection_st.h"
  105. #include "core/or/half_edge_st.h"
  106. #include "core/or/extend_info_st.h"
  107. #include "core/or/or_circuit_st.h"
  108. #include "core/or/origin_circuit_st.h"
  109. /********* START VARIABLES **********/
  110. /** A global list of all circuits at this hop. */
  111. static smartlist_t *global_circuitlist = NULL;
  112. /** A global list of all origin circuits. Every element of this is also
  113. * an element of global_circuitlist. */
  114. static smartlist_t *global_origin_circuit_list = NULL;
  115. /** A list of all the circuits in CIRCUIT_STATE_CHAN_WAIT. */
  116. static smartlist_t *circuits_pending_chans = NULL;
  117. /** List of all the (origin) circuits whose state is
  118. * CIRCUIT_STATE_GUARD_WAIT. */
  119. static smartlist_t *circuits_pending_other_guards = NULL;
  120. /** A list of all the circuits that have been marked with
  121. * circuit_mark_for_close and which are waiting for circuit_about_to_free. */
  122. static smartlist_t *circuits_pending_close = NULL;
  123. static void circuit_free_cpath_node(crypt_path_t *victim);
  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_event_msg_t msg;
  452. tor_assert(circ);
  453. msg.type = OCIRC_MSGTYPE_CEVENT;
  454. msg.u.cevent.gid = circ->global_identifier;
  455. msg.u.cevent.evtype = tp;
  456. msg.u.cevent.reason = reason_code;
  457. msg.u.cevent.onehop = circ->build_state->onehop_tunnel;
  458. ocirc_event_publish(&msg);
  459. return control_event_circuit_status(circ, tp, reason_code);
  460. }
  461. /**
  462. * Helper function to publish a state change message
  463. *
  464. * circuit_set_state() calls this to notify subscribers about a change
  465. * of the state of an origin circuit.
  466. **/
  467. static void
  468. circuit_state_publish(const circuit_t *circ)
  469. {
  470. ocirc_event_msg_t msg;
  471. const origin_circuit_t *ocirc;
  472. if (!CIRCUIT_IS_ORIGIN(circ))
  473. return;
  474. ocirc = CONST_TO_ORIGIN_CIRCUIT(circ);
  475. /* Only inbound OR circuits can be in this state, not origin circuits. */
  476. tor_assert(circ->state != CIRCUIT_STATE_ONIONSKIN_PENDING);
  477. msg.type = OCIRC_MSGTYPE_STATE;
  478. msg.u.state.gid = ocirc->global_identifier;
  479. msg.u.state.state = circ->state;
  480. msg.u.state.onehop = ocirc->build_state->onehop_tunnel;
  481. ocirc_event_publish(&msg);
  482. }
  483. /** Change the state of <b>circ</b> to <b>state</b>, adding it to or removing
  484. * it from lists as appropriate. */
  485. void
  486. circuit_set_state(circuit_t *circ, uint8_t state)
  487. {
  488. tor_assert(circ);
  489. if (state == circ->state)
  490. return;
  491. if (PREDICT_UNLIKELY(!circuits_pending_chans))
  492. circuits_pending_chans = smartlist_new();
  493. if (PREDICT_UNLIKELY(!circuits_pending_other_guards))
  494. circuits_pending_other_guards = smartlist_new();
  495. if (circ->state == CIRCUIT_STATE_CHAN_WAIT) {
  496. /* remove from waiting-circuit list. */
  497. smartlist_remove(circuits_pending_chans, circ);
  498. }
  499. if (state == CIRCUIT_STATE_CHAN_WAIT) {
  500. /* add to waiting-circuit list. */
  501. smartlist_add(circuits_pending_chans, circ);
  502. }
  503. if (circ->state == CIRCUIT_STATE_GUARD_WAIT) {
  504. smartlist_remove(circuits_pending_other_guards, circ);
  505. }
  506. if (state == CIRCUIT_STATE_GUARD_WAIT) {
  507. smartlist_add(circuits_pending_other_guards, circ);
  508. }
  509. if (state == CIRCUIT_STATE_GUARD_WAIT || state == CIRCUIT_STATE_OPEN)
  510. tor_assert(!circ->n_chan_create_cell);
  511. circ->state = state;
  512. circuit_state_publish(circ);
  513. }
  514. /** Append to <b>out</b> all circuits in state CHAN_WAIT waiting for
  515. * the given connection. */
  516. void
  517. circuit_get_all_pending_on_channel(smartlist_t *out, channel_t *chan)
  518. {
  519. tor_assert(out);
  520. tor_assert(chan);
  521. if (!circuits_pending_chans)
  522. return;
  523. SMARTLIST_FOREACH_BEGIN(circuits_pending_chans, circuit_t *, circ) {
  524. if (circ->marked_for_close)
  525. continue;
  526. if (!circ->n_hop)
  527. continue;
  528. tor_assert(circ->state == CIRCUIT_STATE_CHAN_WAIT);
  529. if (tor_digest_is_zero(circ->n_hop->identity_digest)) {
  530. /* Look at addr/port. This is an unkeyed connection. */
  531. if (!channel_matches_extend_info(chan, circ->n_hop))
  532. continue;
  533. } else {
  534. /* We expected a key. See if it's the right one. */
  535. if (tor_memneq(chan->identity_digest,
  536. circ->n_hop->identity_digest, DIGEST_LEN))
  537. continue;
  538. }
  539. smartlist_add(out, circ);
  540. } SMARTLIST_FOREACH_END(circ);
  541. }
  542. /** Return the number of circuits in state CHAN_WAIT, waiting for the given
  543. * channel. */
  544. int
  545. circuit_count_pending_on_channel(channel_t *chan)
  546. {
  547. int cnt;
  548. smartlist_t *sl = smartlist_new();
  549. tor_assert(chan);
  550. circuit_get_all_pending_on_channel(sl, chan);
  551. cnt = smartlist_len(sl);
  552. smartlist_free(sl);
  553. log_debug(LD_CIRC,"or_conn to %s, %d pending circs",
  554. channel_get_canonical_remote_descr(chan),
  555. cnt);
  556. return cnt;
  557. }
  558. /** Remove <b>origin_circ</b> from the global list of origin circuits.
  559. * Called when we are freeing a circuit.
  560. */
  561. static void
  562. circuit_remove_from_origin_circuit_list(origin_circuit_t *origin_circ)
  563. {
  564. int origin_idx = origin_circ->global_origin_circuit_list_idx;
  565. if (origin_idx < 0)
  566. return;
  567. origin_circuit_t *c2;
  568. tor_assert(origin_idx <= smartlist_len(global_origin_circuit_list));
  569. c2 = smartlist_get(global_origin_circuit_list, origin_idx);
  570. tor_assert(origin_circ == c2);
  571. smartlist_del(global_origin_circuit_list, origin_idx);
  572. if (origin_idx < smartlist_len(global_origin_circuit_list)) {
  573. origin_circuit_t *replacement =
  574. smartlist_get(global_origin_circuit_list, origin_idx);
  575. replacement->global_origin_circuit_list_idx = origin_idx;
  576. }
  577. origin_circ->global_origin_circuit_list_idx = -1;
  578. }
  579. /** Add <b>origin_circ</b> to the global list of origin circuits. Called
  580. * when creating the circuit. */
  581. static void
  582. circuit_add_to_origin_circuit_list(origin_circuit_t *origin_circ)
  583. {
  584. tor_assert(origin_circ->global_origin_circuit_list_idx == -1);
  585. smartlist_t *lst = circuit_get_global_origin_circuit_list();
  586. smartlist_add(lst, origin_circ);
  587. origin_circ->global_origin_circuit_list_idx = smartlist_len(lst) - 1;
  588. }
  589. /** Detach from the global circuit list, and deallocate, all
  590. * circuits that have been marked for close.
  591. */
  592. void
  593. circuit_close_all_marked(void)
  594. {
  595. if (circuits_pending_close == NULL)
  596. return;
  597. smartlist_t *lst = circuit_get_global_list();
  598. SMARTLIST_FOREACH_BEGIN(circuits_pending_close, circuit_t *, circ) {
  599. tor_assert(circ->marked_for_close);
  600. /* Remove it from the circuit list. */
  601. int idx = circ->global_circuitlist_idx;
  602. smartlist_del(lst, idx);
  603. if (idx < smartlist_len(lst)) {
  604. circuit_t *replacement = smartlist_get(lst, idx);
  605. replacement->global_circuitlist_idx = idx;
  606. }
  607. circ->global_circuitlist_idx = -1;
  608. /* Remove it from the origin circuit list, if appropriate. */
  609. if (CIRCUIT_IS_ORIGIN(circ)) {
  610. circuit_remove_from_origin_circuit_list(TO_ORIGIN_CIRCUIT(circ));
  611. }
  612. circuit_about_to_free(circ);
  613. circuit_free(circ);
  614. } SMARTLIST_FOREACH_END(circ);
  615. smartlist_clear(circuits_pending_close);
  616. }
  617. /** Return a pointer to the global list of circuits. */
  618. MOCK_IMPL(smartlist_t *,
  619. circuit_get_global_list,(void))
  620. {
  621. if (NULL == global_circuitlist)
  622. global_circuitlist = smartlist_new();
  623. return global_circuitlist;
  624. }
  625. /** Return a pointer to the global list of origin circuits. */
  626. smartlist_t *
  627. circuit_get_global_origin_circuit_list(void)
  628. {
  629. if (NULL == global_origin_circuit_list)
  630. global_origin_circuit_list = smartlist_new();
  631. return global_origin_circuit_list;
  632. }
  633. /**
  634. * Return true if we have any opened general-purpose 3 hop
  635. * origin circuits.
  636. *
  637. * The result from this function is cached for use by
  638. * circuit_any_opened_circuits_cached().
  639. */
  640. int
  641. circuit_any_opened_circuits(void)
  642. {
  643. SMARTLIST_FOREACH_BEGIN(circuit_get_global_origin_circuit_list(),
  644. const origin_circuit_t *, next_circ) {
  645. if (!TO_CIRCUIT(next_circ)->marked_for_close &&
  646. next_circ->has_opened &&
  647. TO_CIRCUIT(next_circ)->state == CIRCUIT_STATE_OPEN &&
  648. TO_CIRCUIT(next_circ)->purpose != CIRCUIT_PURPOSE_C_MEASURE_TIMEOUT &&
  649. next_circ->build_state &&
  650. next_circ->build_state->desired_path_len == DEFAULT_ROUTE_LEN) {
  651. circuit_cache_opened_circuit_state(1);
  652. return 1;
  653. }
  654. } SMARTLIST_FOREACH_END(next_circ);
  655. circuit_cache_opened_circuit_state(0);
  656. return 0;
  657. }
  658. /**
  659. * Cache the "any circuits opened" state, as specified in param
  660. * circuits_are_opened. This is a helper function to update
  661. * the circuit opened status whenever we happen to look at the
  662. * circuit list.
  663. */
  664. void
  665. circuit_cache_opened_circuit_state(int circuits_are_opened)
  666. {
  667. any_opened_circs_cached_val = circuits_are_opened;
  668. }
  669. /**
  670. * Return true if there were any opened circuits since the last call to
  671. * circuit_any_opened_circuits(), or since circuit_expire_building() last
  672. * ran (it runs roughly once per second).
  673. */
  674. int
  675. circuit_any_opened_circuits_cached(void)
  676. {
  677. return any_opened_circs_cached_val;
  678. }
  679. /** Function to make circ-\>state human-readable */
  680. const char *
  681. circuit_state_to_string(int state)
  682. {
  683. static char buf[64];
  684. switch (state) {
  685. case CIRCUIT_STATE_BUILDING: return "doing handshakes";
  686. case CIRCUIT_STATE_ONIONSKIN_PENDING: return "processing the onion";
  687. case CIRCUIT_STATE_CHAN_WAIT: return "connecting to server";
  688. case CIRCUIT_STATE_GUARD_WAIT: return "waiting to see how other "
  689. "guards perform";
  690. case CIRCUIT_STATE_OPEN: return "open";
  691. default:
  692. log_warn(LD_BUG, "Unknown circuit state %d", state);
  693. tor_snprintf(buf, sizeof(buf), "unknown state [%d]", state);
  694. return buf;
  695. }
  696. }
  697. /** Map a circuit purpose to a string suitable to be displayed to a
  698. * controller. */
  699. const char *
  700. circuit_purpose_to_controller_string(uint8_t purpose)
  701. {
  702. static char buf[32];
  703. switch (purpose) {
  704. case CIRCUIT_PURPOSE_OR:
  705. case CIRCUIT_PURPOSE_INTRO_POINT:
  706. case CIRCUIT_PURPOSE_REND_POINT_WAITING:
  707. case CIRCUIT_PURPOSE_REND_ESTABLISHED:
  708. return "SERVER"; /* A controller should never see these, actually. */
  709. case CIRCUIT_PURPOSE_C_GENERAL:
  710. return "GENERAL";
  711. case CIRCUIT_PURPOSE_C_HSDIR_GET:
  712. return "HS_CLIENT_HSDIR";
  713. case CIRCUIT_PURPOSE_C_INTRODUCING:
  714. case CIRCUIT_PURPOSE_C_INTRODUCE_ACK_WAIT:
  715. case CIRCUIT_PURPOSE_C_INTRODUCE_ACKED:
  716. return "HS_CLIENT_INTRO";
  717. case CIRCUIT_PURPOSE_C_ESTABLISH_REND:
  718. case CIRCUIT_PURPOSE_C_REND_READY:
  719. case CIRCUIT_PURPOSE_C_REND_READY_INTRO_ACKED:
  720. case CIRCUIT_PURPOSE_C_REND_JOINED:
  721. return "HS_CLIENT_REND";
  722. case CIRCUIT_PURPOSE_S_HSDIR_POST:
  723. return "HS_SERVICE_HSDIR";
  724. case CIRCUIT_PURPOSE_S_ESTABLISH_INTRO:
  725. case CIRCUIT_PURPOSE_S_INTRO:
  726. return "HS_SERVICE_INTRO";
  727. case CIRCUIT_PURPOSE_S_CONNECT_REND:
  728. case CIRCUIT_PURPOSE_S_REND_JOINED:
  729. return "HS_SERVICE_REND";
  730. case CIRCUIT_PURPOSE_TESTING:
  731. return "TESTING";
  732. case CIRCUIT_PURPOSE_C_MEASURE_TIMEOUT:
  733. return "MEASURE_TIMEOUT";
  734. case CIRCUIT_PURPOSE_CONTROLLER:
  735. return "CONTROLLER";
  736. case CIRCUIT_PURPOSE_PATH_BIAS_TESTING:
  737. return "PATH_BIAS_TESTING";
  738. case CIRCUIT_PURPOSE_HS_VANGUARDS:
  739. return "HS_VANGUARDS";
  740. default:
  741. tor_snprintf(buf, sizeof(buf), "UNKNOWN_%d", (int)purpose);
  742. return buf;
  743. }
  744. }
  745. /** Return a string specifying the state of the hidden-service circuit
  746. * purpose <b>purpose</b>, or NULL if <b>purpose</b> is not a
  747. * hidden-service-related circuit purpose. */
  748. const char *
  749. circuit_purpose_to_controller_hs_state_string(uint8_t purpose)
  750. {
  751. switch (purpose)
  752. {
  753. default:
  754. log_fn(LOG_WARN, LD_BUG,
  755. "Unrecognized circuit purpose: %d",
  756. (int)purpose);
  757. tor_fragile_assert();
  758. /* fall through */
  759. case CIRCUIT_PURPOSE_OR:
  760. case CIRCUIT_PURPOSE_C_GENERAL:
  761. case CIRCUIT_PURPOSE_C_MEASURE_TIMEOUT:
  762. case CIRCUIT_PURPOSE_TESTING:
  763. case CIRCUIT_PURPOSE_CONTROLLER:
  764. case CIRCUIT_PURPOSE_PATH_BIAS_TESTING:
  765. case CIRCUIT_PURPOSE_HS_VANGUARDS:
  766. return NULL;
  767. case CIRCUIT_PURPOSE_INTRO_POINT:
  768. return "OR_HSSI_ESTABLISHED";
  769. case CIRCUIT_PURPOSE_REND_POINT_WAITING:
  770. return "OR_HSCR_ESTABLISHED";
  771. case CIRCUIT_PURPOSE_REND_ESTABLISHED:
  772. return "OR_HS_R_JOINED";
  773. case CIRCUIT_PURPOSE_C_HSDIR_GET:
  774. case CIRCUIT_PURPOSE_C_INTRODUCING:
  775. return "HSCI_CONNECTING";
  776. case CIRCUIT_PURPOSE_C_INTRODUCE_ACK_WAIT:
  777. return "HSCI_INTRO_SENT";
  778. case CIRCUIT_PURPOSE_C_INTRODUCE_ACKED:
  779. return "HSCI_DONE";
  780. case CIRCUIT_PURPOSE_C_ESTABLISH_REND:
  781. return "HSCR_CONNECTING";
  782. case CIRCUIT_PURPOSE_C_REND_READY:
  783. return "HSCR_ESTABLISHED_IDLE";
  784. case CIRCUIT_PURPOSE_C_REND_READY_INTRO_ACKED:
  785. return "HSCR_ESTABLISHED_WAITING";
  786. case CIRCUIT_PURPOSE_C_REND_JOINED:
  787. return "HSCR_JOINED";
  788. case CIRCUIT_PURPOSE_S_HSDIR_POST:
  789. case CIRCUIT_PURPOSE_S_ESTABLISH_INTRO:
  790. return "HSSI_CONNECTING";
  791. case CIRCUIT_PURPOSE_S_INTRO:
  792. return "HSSI_ESTABLISHED";
  793. case CIRCUIT_PURPOSE_S_CONNECT_REND:
  794. return "HSSR_CONNECTING";
  795. case CIRCUIT_PURPOSE_S_REND_JOINED:
  796. return "HSSR_JOINED";
  797. }
  798. }
  799. /** Return a human-readable string for the circuit purpose <b>purpose</b>. */
  800. const char *
  801. circuit_purpose_to_string(uint8_t purpose)
  802. {
  803. static char buf[32];
  804. switch (purpose)
  805. {
  806. case CIRCUIT_PURPOSE_OR:
  807. return "Circuit at relay";
  808. case CIRCUIT_PURPOSE_INTRO_POINT:
  809. return "Acting as intro point";
  810. case CIRCUIT_PURPOSE_REND_POINT_WAITING:
  811. return "Acting as rendezvous (pending)";
  812. case CIRCUIT_PURPOSE_REND_ESTABLISHED:
  813. return "Acting as rendezvous (established)";
  814. case CIRCUIT_PURPOSE_C_GENERAL:
  815. return "General-purpose client";
  816. case CIRCUIT_PURPOSE_C_INTRODUCING:
  817. return "Hidden service client: Connecting to intro point";
  818. case CIRCUIT_PURPOSE_C_INTRODUCE_ACK_WAIT:
  819. return "Hidden service client: Waiting for ack from intro point";
  820. case CIRCUIT_PURPOSE_C_INTRODUCE_ACKED:
  821. return "Hidden service client: Received ack from intro point";
  822. case CIRCUIT_PURPOSE_C_ESTABLISH_REND:
  823. return "Hidden service client: Establishing rendezvous point";
  824. case CIRCUIT_PURPOSE_C_REND_READY:
  825. return "Hidden service client: Pending rendezvous point";
  826. case CIRCUIT_PURPOSE_C_REND_READY_INTRO_ACKED:
  827. return "Hidden service client: Pending rendezvous point (ack received)";
  828. case CIRCUIT_PURPOSE_C_REND_JOINED:
  829. return "Hidden service client: Active rendezvous point";
  830. case CIRCUIT_PURPOSE_C_HSDIR_GET:
  831. return "Hidden service client: Fetching HS descriptor";
  832. case CIRCUIT_PURPOSE_C_MEASURE_TIMEOUT:
  833. return "Measuring circuit timeout";
  834. case CIRCUIT_PURPOSE_S_ESTABLISH_INTRO:
  835. return "Hidden service: Establishing introduction point";
  836. case CIRCUIT_PURPOSE_S_INTRO:
  837. return "Hidden service: Introduction point";
  838. case CIRCUIT_PURPOSE_S_CONNECT_REND:
  839. return "Hidden service: Connecting to rendezvous point";
  840. case CIRCUIT_PURPOSE_S_REND_JOINED:
  841. return "Hidden service: Active rendezvous point";
  842. case CIRCUIT_PURPOSE_S_HSDIR_POST:
  843. return "Hidden service: Uploading HS descriptor";
  844. case CIRCUIT_PURPOSE_TESTING:
  845. return "Testing circuit";
  846. case CIRCUIT_PURPOSE_CONTROLLER:
  847. return "Circuit made by controller";
  848. case CIRCUIT_PURPOSE_PATH_BIAS_TESTING:
  849. return "Path-bias testing circuit";
  850. case CIRCUIT_PURPOSE_HS_VANGUARDS:
  851. return "Hidden service: Pre-built vanguard circuit";
  852. default:
  853. tor_snprintf(buf, sizeof(buf), "UNKNOWN_%d", (int)purpose);
  854. return buf;
  855. }
  856. }
  857. /** Pick a reasonable package_window to start out for our circuits.
  858. * Originally this was hard-coded at 1000, but now the consensus votes
  859. * on the answer. See proposal 168. */
  860. int32_t
  861. circuit_initial_package_window(void)
  862. {
  863. int32_t num = networkstatus_get_param(NULL, "circwindow", CIRCWINDOW_START,
  864. CIRCWINDOW_START_MIN,
  865. CIRCWINDOW_START_MAX);
  866. /* If the consensus tells us a negative number, we'd assert. */
  867. if (num < 0)
  868. num = CIRCWINDOW_START;
  869. return num;
  870. }
  871. /** Initialize the common elements in a circuit_t, and add it to the global
  872. * list. */
  873. static void
  874. init_circuit_base(circuit_t *circ)
  875. {
  876. tor_gettimeofday(&circ->timestamp_created);
  877. // Gets reset when we send CREATE_FAST.
  878. // circuit_expire_building() expects these to be equal
  879. // until the orconn is built.
  880. circ->timestamp_began = circ->timestamp_created;
  881. circ->package_window = circuit_initial_package_window();
  882. circ->deliver_window = CIRCWINDOW_START;
  883. cell_queue_init(&circ->n_chan_cells);
  884. smartlist_add(circuit_get_global_list(), circ);
  885. circ->global_circuitlist_idx = smartlist_len(circuit_get_global_list()) - 1;
  886. }
  887. /** If we haven't yet decided on a good timeout value for circuit
  888. * building, we close idle circuits aggressively so we can get more
  889. * data points. These are the default, min, and max consensus values */
  890. #define DFLT_IDLE_TIMEOUT_WHILE_LEARNING (3*60)
  891. #define MIN_IDLE_TIMEOUT_WHILE_LEARNING (10)
  892. #define MAX_IDLE_TIMEOUT_WHILE_LEARNING (1000*60)
  893. /** Allocate space for a new circuit, initializing with <b>p_circ_id</b>
  894. * and <b>p_conn</b>. Add it to the global circuit list.
  895. */
  896. origin_circuit_t *
  897. origin_circuit_new(void)
  898. {
  899. origin_circuit_t *circ;
  900. /* never zero, since a global ID of 0 is treated specially by the
  901. * controller */
  902. static uint32_t n_circuits_allocated = 1;
  903. circ = tor_malloc_zero(sizeof(origin_circuit_t));
  904. circ->base_.magic = ORIGIN_CIRCUIT_MAGIC;
  905. circ->next_stream_id = crypto_rand_int(1<<16);
  906. circ->global_identifier = n_circuits_allocated++;
  907. circ->remaining_relay_early_cells = MAX_RELAY_EARLY_CELLS_PER_CIRCUIT;
  908. circ->remaining_relay_early_cells -= crypto_rand_int(2);
  909. init_circuit_base(TO_CIRCUIT(circ));
  910. /* Add to origin-list. */
  911. circ->global_origin_circuit_list_idx = -1;
  912. circuit_add_to_origin_circuit_list(circ);
  913. circuit_build_times_update_last_circ(get_circuit_build_times_mutable());
  914. if (! circuit_build_times_disabled(get_options()) &&
  915. circuit_build_times_needs_circuits(get_circuit_build_times())) {
  916. /* Circuits should be shorter lived if we need more of them
  917. * for learning a good build timeout */
  918. circ->circuit_idle_timeout =
  919. networkstatus_get_param(NULL, "cbtlearntimeout",
  920. DFLT_IDLE_TIMEOUT_WHILE_LEARNING,
  921. MIN_IDLE_TIMEOUT_WHILE_LEARNING,
  922. MAX_IDLE_TIMEOUT_WHILE_LEARNING);
  923. } else {
  924. // This should always be larger than the current port prediction time
  925. // remaining, or else we'll end up with the case where a circuit times out
  926. // and another one is built, effectively doubling the timeout window.
  927. //
  928. // We also randomize it by up to 5% more (ie 5% of 0 to 3600 seconds,
  929. // depending on how much circuit prediction time is remaining) so that
  930. // we don't close a bunch of unused circuits all at the same time.
  931. int prediction_time_remaining =
  932. predicted_ports_prediction_time_remaining(time(NULL));
  933. circ->circuit_idle_timeout = prediction_time_remaining+1+
  934. crypto_rand_int(1+prediction_time_remaining/20);
  935. if (circ->circuit_idle_timeout <= 0) {
  936. log_warn(LD_BUG,
  937. "Circuit chose a negative idle timeout of %d based on "
  938. "%d seconds of predictive building remaining.",
  939. circ->circuit_idle_timeout,
  940. prediction_time_remaining);
  941. circ->circuit_idle_timeout =
  942. networkstatus_get_param(NULL, "cbtlearntimeout",
  943. DFLT_IDLE_TIMEOUT_WHILE_LEARNING,
  944. MIN_IDLE_TIMEOUT_WHILE_LEARNING,
  945. MAX_IDLE_TIMEOUT_WHILE_LEARNING);
  946. }
  947. log_info(LD_CIRC,
  948. "Circuit %"PRIu32" chose an idle timeout of %d based on "
  949. "%d seconds of predictive building remaining.",
  950. (circ->global_identifier),
  951. circ->circuit_idle_timeout,
  952. prediction_time_remaining);
  953. }
  954. return circ;
  955. }
  956. /** Allocate a new or_circuit_t, connected to <b>p_chan</b> as
  957. * <b>p_circ_id</b>. If <b>p_chan</b> is NULL, the circuit is unattached. */
  958. or_circuit_t *
  959. or_circuit_new(circid_t p_circ_id, channel_t *p_chan)
  960. {
  961. /* CircIDs */
  962. or_circuit_t *circ;
  963. circ = tor_malloc_zero(sizeof(or_circuit_t));
  964. circ->base_.magic = OR_CIRCUIT_MAGIC;
  965. if (p_chan)
  966. circuit_set_p_circid_chan(circ, p_circ_id, p_chan);
  967. circ->remaining_relay_early_cells = MAX_RELAY_EARLY_CELLS_PER_CIRCUIT;
  968. cell_queue_init(&circ->p_chan_cells);
  969. init_circuit_base(TO_CIRCUIT(circ));
  970. return circ;
  971. }
  972. /** Free all storage held in circ->testing_cell_stats */
  973. void
  974. circuit_clear_testing_cell_stats(circuit_t *circ)
  975. {
  976. if (!circ || !circ->testing_cell_stats)
  977. return;
  978. SMARTLIST_FOREACH(circ->testing_cell_stats, testing_cell_stats_entry_t *,
  979. ent, tor_free(ent));
  980. smartlist_free(circ->testing_cell_stats);
  981. circ->testing_cell_stats = NULL;
  982. }
  983. /** Deallocate space associated with circ.
  984. */
  985. STATIC void
  986. circuit_free_(circuit_t *circ)
  987. {
  988. circid_t n_circ_id = 0;
  989. void *mem;
  990. size_t memlen;
  991. int should_free = 1;
  992. if (!circ)
  993. return;
  994. /* We keep a copy of this so we can log its value before it gets unset. */
  995. n_circ_id = circ->n_circ_id;
  996. circuit_clear_testing_cell_stats(circ);
  997. /* Cleanup circuit from anything HS v3 related. We also do this when the
  998. * circuit is closed. This is to avoid any code path that free registered
  999. * circuits without closing them before. This needs to be done before the
  1000. * hs identifier is freed. */
  1001. hs_circ_cleanup(circ);
  1002. if (CIRCUIT_IS_ORIGIN(circ)) {
  1003. origin_circuit_t *ocirc = TO_ORIGIN_CIRCUIT(circ);
  1004. mem = ocirc;
  1005. memlen = sizeof(origin_circuit_t);
  1006. tor_assert(circ->magic == ORIGIN_CIRCUIT_MAGIC);
  1007. circuit_remove_from_origin_circuit_list(ocirc);
  1008. if (ocirc->half_streams) {
  1009. SMARTLIST_FOREACH_BEGIN(ocirc->half_streams, half_edge_t *,
  1010. half_conn) {
  1011. half_edge_free(half_conn);
  1012. } SMARTLIST_FOREACH_END(half_conn);
  1013. smartlist_free(ocirc->half_streams);
  1014. }
  1015. if (ocirc->build_state) {
  1016. extend_info_free(ocirc->build_state->chosen_exit);
  1017. circuit_free_cpath_node(ocirc->build_state->pending_final_cpath);
  1018. cpath_ref_decref(ocirc->build_state->service_pending_final_cpath_ref);
  1019. }
  1020. tor_free(ocirc->build_state);
  1021. /* Cancel before freeing, if we haven't already succeeded or failed. */
  1022. if (ocirc->guard_state) {
  1023. entry_guard_cancel(&ocirc->guard_state);
  1024. }
  1025. circuit_guard_state_free(ocirc->guard_state);
  1026. circuit_clear_cpath(ocirc);
  1027. crypto_pk_free(ocirc->intro_key);
  1028. rend_data_free(ocirc->rend_data);
  1029. /* Finally, free the identifier of the circuit and nullify it so multiple
  1030. * cleanup will work. */
  1031. hs_ident_circuit_free(ocirc->hs_ident);
  1032. ocirc->hs_ident = NULL;
  1033. tor_free(ocirc->dest_address);
  1034. if (ocirc->socks_username) {
  1035. memwipe(ocirc->socks_username, 0x12, ocirc->socks_username_len);
  1036. tor_free(ocirc->socks_username);
  1037. }
  1038. if (ocirc->socks_password) {
  1039. memwipe(ocirc->socks_password, 0x06, ocirc->socks_password_len);
  1040. tor_free(ocirc->socks_password);
  1041. }
  1042. addr_policy_list_free(ocirc->prepend_policy);
  1043. } else {
  1044. or_circuit_t *ocirc = TO_OR_CIRCUIT(circ);
  1045. /* Remember cell statistics for this circuit before deallocating. */
  1046. if (get_options()->CellStatistics)
  1047. rep_hist_buffer_stats_add_circ(circ, time(NULL));
  1048. mem = ocirc;
  1049. memlen = sizeof(or_circuit_t);
  1050. tor_assert(circ->magic == OR_CIRCUIT_MAGIC);
  1051. should_free = (ocirc->workqueue_entry == NULL);
  1052. relay_crypto_clear(&ocirc->crypto);
  1053. if (ocirc->rend_splice) {
  1054. or_circuit_t *other = ocirc->rend_splice;
  1055. tor_assert(other->base_.magic == OR_CIRCUIT_MAGIC);
  1056. other->rend_splice = NULL;
  1057. }
  1058. /* remove from map. */
  1059. circuit_set_p_circid_chan(ocirc, 0, NULL);
  1060. /* Clear cell queue _after_ removing it from the map. Otherwise our
  1061. * "active" checks will be violated. */
  1062. cell_queue_clear(&ocirc->p_chan_cells);
  1063. }
  1064. extend_info_free(circ->n_hop);
  1065. tor_free(circ->n_chan_create_cell);
  1066. if (circ->global_circuitlist_idx != -1) {
  1067. int idx = circ->global_circuitlist_idx;
  1068. circuit_t *c2 = smartlist_get(global_circuitlist, idx);
  1069. tor_assert(c2 == circ);
  1070. smartlist_del(global_circuitlist, idx);
  1071. if (idx < smartlist_len(global_circuitlist)) {
  1072. c2 = smartlist_get(global_circuitlist, idx);
  1073. c2->global_circuitlist_idx = idx;
  1074. }
  1075. }
  1076. /* Remove from map. */
  1077. circuit_set_n_circid_chan(circ, 0, NULL);
  1078. /* Clear cell queue _after_ removing it from the map. Otherwise our
  1079. * "active" checks will be violated. */
  1080. cell_queue_clear(&circ->n_chan_cells);
  1081. log_info(LD_CIRC, "Circuit %u (id: %" PRIu32 ") has been freed.",
  1082. n_circ_id,
  1083. CIRCUIT_IS_ORIGIN(circ) ?
  1084. TO_ORIGIN_CIRCUIT(circ)->global_identifier : 0);
  1085. /* Free any circuit padding structures */
  1086. circpad_circuit_free_all_machineinfos(circ);
  1087. if (should_free) {
  1088. memwipe(mem, 0xAA, memlen); /* poison memory */
  1089. tor_free(mem);
  1090. } else {
  1091. /* If we made it here, this is an or_circuit_t that still has a pending
  1092. * cpuworker request which we weren't able to cancel. Instead, set up
  1093. * the magic value so that when the reply comes back, we'll know to discard
  1094. * the reply and free this structure.
  1095. */
  1096. memwipe(mem, 0xAA, memlen);
  1097. circ->magic = DEAD_CIRCUIT_MAGIC;
  1098. }
  1099. }
  1100. /** Deallocate the linked list circ-><b>cpath</b>, and remove the cpath from
  1101. * <b>circ</b>. */
  1102. void
  1103. circuit_clear_cpath(origin_circuit_t *circ)
  1104. {
  1105. crypt_path_t *victim, *head, *cpath;
  1106. head = cpath = circ->cpath;
  1107. if (!cpath)
  1108. return;
  1109. /* it's a circular list, so we have to notice when we've
  1110. * gone through it once. */
  1111. while (cpath->next && cpath->next != head) {
  1112. victim = cpath;
  1113. cpath = victim->next;
  1114. circuit_free_cpath_node(victim);
  1115. }
  1116. circuit_free_cpath_node(cpath);
  1117. circ->cpath = NULL;
  1118. }
  1119. /** Release all storage held by circuits. */
  1120. void
  1121. circuit_free_all(void)
  1122. {
  1123. smartlist_t *lst = circuit_get_global_list();
  1124. SMARTLIST_FOREACH_BEGIN(lst, circuit_t *, tmp) {
  1125. if (! CIRCUIT_IS_ORIGIN(tmp)) {
  1126. or_circuit_t *or_circ = TO_OR_CIRCUIT(tmp);
  1127. while (or_circ->resolving_streams) {
  1128. edge_connection_t *next_conn;
  1129. next_conn = or_circ->resolving_streams->next_stream;
  1130. connection_free_(TO_CONN(or_circ->resolving_streams));
  1131. or_circ->resolving_streams = next_conn;
  1132. }
  1133. }
  1134. tmp->global_circuitlist_idx = -1;
  1135. circuit_about_to_free_atexit(tmp);
  1136. circuit_free(tmp);
  1137. SMARTLIST_DEL_CURRENT(lst, tmp);
  1138. } SMARTLIST_FOREACH_END(tmp);
  1139. smartlist_free(lst);
  1140. global_circuitlist = NULL;
  1141. smartlist_free(global_origin_circuit_list);
  1142. global_origin_circuit_list = NULL;
  1143. smartlist_free(circuits_pending_chans);
  1144. circuits_pending_chans = NULL;
  1145. smartlist_free(circuits_pending_close);
  1146. circuits_pending_close = NULL;
  1147. smartlist_free(circuits_pending_other_guards);
  1148. circuits_pending_other_guards = NULL;
  1149. {
  1150. chan_circid_circuit_map_t **elt, **next, *c;
  1151. for (elt = HT_START(chan_circid_map, &chan_circid_map);
  1152. elt;
  1153. elt = next) {
  1154. c = *elt;
  1155. next = HT_NEXT_RMV(chan_circid_map, &chan_circid_map, elt);
  1156. tor_assert(c->circuit == NULL);
  1157. tor_free(c);
  1158. }
  1159. }
  1160. HT_CLEAR(chan_circid_map, &chan_circid_map);
  1161. }
  1162. /** Deallocate space associated with the cpath node <b>victim</b>. */
  1163. static void
  1164. circuit_free_cpath_node(crypt_path_t *victim)
  1165. {
  1166. if (!victim)
  1167. return;
  1168. relay_crypto_clear(&victim->crypto);
  1169. onion_handshake_state_release(&victim->handshake_state);
  1170. crypto_dh_free(victim->rend_dh_handshake_state);
  1171. extend_info_free(victim->extend_info);
  1172. memwipe(victim, 0xBB, sizeof(crypt_path_t)); /* poison memory */
  1173. tor_free(victim);
  1174. }
  1175. /** Release a crypt_path_reference_t*, which may be NULL. */
  1176. static void
  1177. cpath_ref_decref(crypt_path_reference_t *cpath_ref)
  1178. {
  1179. if (cpath_ref != NULL) {
  1180. if (--(cpath_ref->refcount) == 0) {
  1181. circuit_free_cpath_node(cpath_ref->cpath);
  1182. tor_free(cpath_ref);
  1183. }
  1184. }
  1185. }
  1186. /** A helper function for circuit_dump_by_conn() below. Log a bunch
  1187. * of information about circuit <b>circ</b>.
  1188. */
  1189. static void
  1190. circuit_dump_conn_details(int severity,
  1191. circuit_t *circ,
  1192. int conn_array_index,
  1193. const char *type,
  1194. circid_t this_circid,
  1195. circid_t other_circid)
  1196. {
  1197. tor_log(severity, LD_CIRC, "Conn %d has %s circuit: circID %u "
  1198. "(other side %u), state %d (%s), born %ld:",
  1199. conn_array_index, type, (unsigned)this_circid, (unsigned)other_circid,
  1200. circ->state, circuit_state_to_string(circ->state),
  1201. (long)circ->timestamp_began.tv_sec);
  1202. if (CIRCUIT_IS_ORIGIN(circ)) { /* circ starts at this node */
  1203. circuit_log_path(severity, LD_CIRC, TO_ORIGIN_CIRCUIT(circ));
  1204. }
  1205. }
  1206. /** Log, at severity <b>severity</b>, information about each circuit
  1207. * that is connected to <b>conn</b>.
  1208. */
  1209. void
  1210. circuit_dump_by_conn(connection_t *conn, int severity)
  1211. {
  1212. edge_connection_t *tmpconn;
  1213. SMARTLIST_FOREACH_BEGIN(circuit_get_global_list(), circuit_t *, circ) {
  1214. circid_t n_circ_id = circ->n_circ_id, p_circ_id = 0;
  1215. if (circ->marked_for_close) {
  1216. continue;
  1217. }
  1218. if (!CIRCUIT_IS_ORIGIN(circ)) {
  1219. p_circ_id = TO_OR_CIRCUIT(circ)->p_circ_id;
  1220. }
  1221. if (CIRCUIT_IS_ORIGIN(circ)) {
  1222. for (tmpconn=TO_ORIGIN_CIRCUIT(circ)->p_streams; tmpconn;
  1223. tmpconn=tmpconn->next_stream) {
  1224. if (TO_CONN(tmpconn) == conn) {
  1225. circuit_dump_conn_details(severity, circ, conn->conn_array_index,
  1226. "App-ward", p_circ_id, n_circ_id);
  1227. }
  1228. }
  1229. }
  1230. if (! CIRCUIT_IS_ORIGIN(circ)) {
  1231. for (tmpconn=TO_OR_CIRCUIT(circ)->n_streams; tmpconn;
  1232. tmpconn=tmpconn->next_stream) {
  1233. if (TO_CONN(tmpconn) == conn) {
  1234. circuit_dump_conn_details(severity, circ, conn->conn_array_index,
  1235. "Exit-ward", n_circ_id, p_circ_id);
  1236. }
  1237. }
  1238. }
  1239. }
  1240. SMARTLIST_FOREACH_END(circ);
  1241. }
  1242. /** Return the circuit whose global ID is <b>id</b>, or NULL if no
  1243. * such circuit exists. */
  1244. origin_circuit_t *
  1245. circuit_get_by_global_id(uint32_t id)
  1246. {
  1247. SMARTLIST_FOREACH_BEGIN(circuit_get_global_list(), circuit_t *, circ) {
  1248. if (CIRCUIT_IS_ORIGIN(circ) &&
  1249. TO_ORIGIN_CIRCUIT(circ)->global_identifier == id) {
  1250. if (circ->marked_for_close)
  1251. return NULL;
  1252. else
  1253. return TO_ORIGIN_CIRCUIT(circ);
  1254. }
  1255. }
  1256. SMARTLIST_FOREACH_END(circ);
  1257. return NULL;
  1258. }
  1259. /** Return a circ such that:
  1260. * - circ-\>n_circ_id or circ-\>p_circ_id is equal to <b>circ_id</b>, and
  1261. * - circ is attached to <b>chan</b>, either as p_chan or n_chan.
  1262. * Return NULL if no such circuit exists.
  1263. *
  1264. * If <b>found_entry_out</b> is provided, set it to true if we have a
  1265. * placeholder entry for circid/chan, and leave it unset otherwise.
  1266. */
  1267. static inline circuit_t *
  1268. circuit_get_by_circid_channel_impl(circid_t circ_id, channel_t *chan,
  1269. int *found_entry_out)
  1270. {
  1271. chan_circid_circuit_map_t search;
  1272. chan_circid_circuit_map_t *found;
  1273. if (_last_circid_chan_ent &&
  1274. circ_id == _last_circid_chan_ent->circ_id &&
  1275. chan == _last_circid_chan_ent->chan) {
  1276. found = _last_circid_chan_ent;
  1277. } else {
  1278. search.circ_id = circ_id;
  1279. search.chan = chan;
  1280. found = HT_FIND(chan_circid_map, &chan_circid_map, &search);
  1281. _last_circid_chan_ent = found;
  1282. }
  1283. if (found && found->circuit) {
  1284. log_debug(LD_CIRC,
  1285. "circuit_get_by_circid_channel_impl() returning circuit %p for"
  1286. " circ_id %u, channel ID %"PRIu64 " (%p)",
  1287. found->circuit, (unsigned)circ_id,
  1288. (chan->global_identifier), chan);
  1289. if (found_entry_out)
  1290. *found_entry_out = 1;
  1291. return found->circuit;
  1292. }
  1293. log_debug(LD_CIRC,
  1294. "circuit_get_by_circid_channel_impl() found %s for"
  1295. " circ_id %u, channel ID %"PRIu64 " (%p)",
  1296. found ? "placeholder" : "nothing",
  1297. (unsigned)circ_id,
  1298. (chan->global_identifier), chan);
  1299. if (found_entry_out)
  1300. *found_entry_out = found ? 1 : 0;
  1301. return NULL;
  1302. /* The rest of this checks for bugs. Disabled by default. */
  1303. /* We comment it out because coverity complains otherwise.
  1304. {
  1305. circuit_t *circ;
  1306. TOR_LIST_FOREACH(circ, &global_circuitlist, head) {
  1307. if (! CIRCUIT_IS_ORIGIN(circ)) {
  1308. or_circuit_t *or_circ = TO_OR_CIRCUIT(circ);
  1309. if (or_circ->p_chan == chan && or_circ->p_circ_id == circ_id) {
  1310. log_warn(LD_BUG,
  1311. "circuit matches p_chan, but not in hash table (Bug!)");
  1312. return circ;
  1313. }
  1314. }
  1315. if (circ->n_chan == chan && circ->n_circ_id == circ_id) {
  1316. log_warn(LD_BUG,
  1317. "circuit matches n_chan, but not in hash table (Bug!)");
  1318. return circ;
  1319. }
  1320. }
  1321. return NULL;
  1322. } */
  1323. }
  1324. /** Return a circ such that:
  1325. * - circ-\>n_circ_id or circ-\>p_circ_id is equal to <b>circ_id</b>, and
  1326. * - circ is attached to <b>chan</b>, either as p_chan or n_chan.
  1327. * - circ is not marked for close.
  1328. * Return NULL if no such circuit exists.
  1329. */
  1330. circuit_t *
  1331. circuit_get_by_circid_channel(circid_t circ_id, channel_t *chan)
  1332. {
  1333. circuit_t *circ = circuit_get_by_circid_channel_impl(circ_id, chan, NULL);
  1334. if (!circ || circ->marked_for_close)
  1335. return NULL;
  1336. else
  1337. return circ;
  1338. }
  1339. /** Return a circ such that:
  1340. * - circ-\>n_circ_id or circ-\>p_circ_id is equal to <b>circ_id</b>, and
  1341. * - circ is attached to <b>chan</b>, either as p_chan or n_chan.
  1342. * Return NULL if no such circuit exists.
  1343. */
  1344. circuit_t *
  1345. circuit_get_by_circid_channel_even_if_marked(circid_t circ_id,
  1346. channel_t *chan)
  1347. {
  1348. return circuit_get_by_circid_channel_impl(circ_id, chan, NULL);
  1349. }
  1350. /** Return true iff the circuit ID <b>circ_id</b> is currently used by a
  1351. * circuit, marked or not, on <b>chan</b>, or if the circ ID is reserved until
  1352. * a queued destroy cell can be sent.
  1353. *
  1354. * (Return 1 if the circuit is present, marked or not; Return 2
  1355. * if the circuit ID is pending a destroy.)
  1356. **/
  1357. int
  1358. circuit_id_in_use_on_channel(circid_t circ_id, channel_t *chan)
  1359. {
  1360. int found = 0;
  1361. if (circuit_get_by_circid_channel_impl(circ_id, chan, &found) != NULL)
  1362. return 1;
  1363. if (found)
  1364. return 2;
  1365. return 0;
  1366. }
  1367. /** Helper for debugging 12184. Returns the time since which 'circ_id' has
  1368. * been marked unusable on 'chan'. */
  1369. time_t
  1370. circuit_id_when_marked_unusable_on_channel(circid_t circ_id, channel_t *chan)
  1371. {
  1372. chan_circid_circuit_map_t search;
  1373. chan_circid_circuit_map_t *found;
  1374. memset(&search, 0, sizeof(search));
  1375. search.circ_id = circ_id;
  1376. search.chan = chan;
  1377. found = HT_FIND(chan_circid_map, &chan_circid_map, &search);
  1378. if (! found || found->circuit)
  1379. return 0;
  1380. return found->made_placeholder_at;
  1381. }
  1382. /** Return the circuit that a given edge connection is using. */
  1383. circuit_t *
  1384. circuit_get_by_edge_conn(edge_connection_t *conn)
  1385. {
  1386. circuit_t *circ;
  1387. circ = conn->on_circuit;
  1388. tor_assert(!circ ||
  1389. (CIRCUIT_IS_ORIGIN(circ) ? circ->magic == ORIGIN_CIRCUIT_MAGIC
  1390. : circ->magic == OR_CIRCUIT_MAGIC));
  1391. return circ;
  1392. }
  1393. /** For each circuit that has <b>chan</b> as n_chan or p_chan, unlink the
  1394. * circuit from the chan,circid map, and mark it for close if it hasn't
  1395. * been marked already.
  1396. */
  1397. void
  1398. circuit_unlink_all_from_channel(channel_t *chan, int reason)
  1399. {
  1400. smartlist_t *detached = smartlist_new();
  1401. /* #define DEBUG_CIRCUIT_UNLINK_ALL */
  1402. channel_unlink_all_circuits(chan, detached);
  1403. #ifdef DEBUG_CIRCUIT_UNLINK_ALL
  1404. {
  1405. smartlist_t *detached_2 = smartlist_new();
  1406. int mismatch = 0, badlen = 0;
  1407. SMARTLIST_FOREACH_BEGIN(circuit_get_global_list(), circuit_t *, circ) {
  1408. if (circ->n_chan == chan ||
  1409. (!CIRCUIT_IS_ORIGIN(circ) &&
  1410. TO_OR_CIRCUIT(circ)->p_chan == chan)) {
  1411. smartlist_add(detached_2, circ);
  1412. }
  1413. }
  1414. SMARTLIST_FOREACH_END(circ);
  1415. if (smartlist_len(detached) != smartlist_len(detached_2)) {
  1416. log_warn(LD_BUG, "List of detached circuits had the wrong length! "
  1417. "(got %d, should have gotten %d)",
  1418. (int)smartlist_len(detached),
  1419. (int)smartlist_len(detached_2));
  1420. badlen = 1;
  1421. }
  1422. smartlist_sort_pointers(detached);
  1423. smartlist_sort_pointers(detached_2);
  1424. SMARTLIST_FOREACH(detached, circuit_t *, c,
  1425. if (c != smartlist_get(detached_2, c_sl_idx))
  1426. mismatch = 1;
  1427. );
  1428. if (mismatch)
  1429. log_warn(LD_BUG, "Mismatch in list of detached circuits.");
  1430. if (badlen || mismatch) {
  1431. smartlist_free(detached);
  1432. detached = detached_2;
  1433. } else {
  1434. log_notice(LD_CIRC, "List of %d circuits was as expected.",
  1435. (int)smartlist_len(detached));
  1436. smartlist_free(detached_2);
  1437. }
  1438. }
  1439. #endif /* defined(DEBUG_CIRCUIT_UNLINK_ALL) */
  1440. SMARTLIST_FOREACH_BEGIN(detached, circuit_t *, circ) {
  1441. int mark = 0;
  1442. if (circ->n_chan == chan) {
  1443. circuit_set_n_circid_chan(circ, 0, NULL);
  1444. mark = 1;
  1445. /* If we didn't request this closure, pass the remote
  1446. * bit to mark_for_close. */
  1447. if (chan->reason_for_closing != CHANNEL_CLOSE_REQUESTED)
  1448. reason |= END_CIRC_REASON_FLAG_REMOTE;
  1449. }
  1450. if (! CIRCUIT_IS_ORIGIN(circ)) {
  1451. or_circuit_t *or_circ = TO_OR_CIRCUIT(circ);
  1452. if (or_circ->p_chan == chan) {
  1453. circuit_set_p_circid_chan(or_circ, 0, NULL);
  1454. mark = 1;
  1455. }
  1456. }
  1457. if (!mark) {
  1458. log_warn(LD_BUG, "Circuit on detached list which I had no reason "
  1459. "to mark");
  1460. continue;
  1461. }
  1462. if (!circ->marked_for_close)
  1463. circuit_mark_for_close(circ, reason);
  1464. } SMARTLIST_FOREACH_END(circ);
  1465. smartlist_free(detached);
  1466. }
  1467. /** Return a circ such that
  1468. * - circ-\>rend_data-\>onion_address is equal to
  1469. * <b>rend_data</b>-\>onion_address,
  1470. * - circ-\>rend_data-\>rend_cookie is equal to
  1471. * <b>rend_data</b>-\>rend_cookie, and
  1472. * - circ-\>purpose is equal to CIRCUIT_PURPOSE_C_REND_READY.
  1473. *
  1474. * Return NULL if no such circuit exists.
  1475. */
  1476. origin_circuit_t *
  1477. circuit_get_ready_rend_circ_by_rend_data(const rend_data_t *rend_data)
  1478. {
  1479. SMARTLIST_FOREACH_BEGIN(circuit_get_global_list(), circuit_t *, circ) {
  1480. if (!circ->marked_for_close &&
  1481. circ->purpose == CIRCUIT_PURPOSE_C_REND_READY) {
  1482. origin_circuit_t *ocirc = TO_ORIGIN_CIRCUIT(circ);
  1483. if (ocirc->rend_data == NULL) {
  1484. continue;
  1485. }
  1486. if (!rend_cmp_service_ids(rend_data_get_address(rend_data),
  1487. rend_data_get_address(ocirc->rend_data)) &&
  1488. tor_memeq(ocirc->rend_data->rend_cookie,
  1489. rend_data->rend_cookie,
  1490. REND_COOKIE_LEN))
  1491. return ocirc;
  1492. }
  1493. }
  1494. SMARTLIST_FOREACH_END(circ);
  1495. return NULL;
  1496. }
  1497. /** Return the first introduction circuit originating from the global circuit
  1498. * list after <b>start</b> or at the start of the list if <b>start</b> is
  1499. * NULL. Return NULL if no circuit is found.
  1500. *
  1501. * If <b>want_client_circ</b> is true, then we are looking for client-side
  1502. * introduction circuits: A client introduction point circuit has a purpose of
  1503. * either CIRCUIT_PURPOSE_C_INTRODUCING, CIRCUIT_PURPOSE_C_INTRODUCE_ACK_WAIT
  1504. * or CIRCUIT_PURPOSE_C_INTRODUCE_ACKED. This does not return a circuit marked
  1505. * for close, but it returns circuits regardless of their circuit state.
  1506. *
  1507. * If <b>want_client_circ</b> is false, then we are looking for service-side
  1508. * introduction circuits: A service introduction point circuit has a purpose of
  1509. * either CIRCUIT_PURPOSE_S_ESTABLISH_INTRO or CIRCUIT_PURPOSE_S_INTRO. This
  1510. * does not return circuits marked for close, or in any state other than open.
  1511. */
  1512. origin_circuit_t *
  1513. circuit_get_next_intro_circ(const origin_circuit_t *start,
  1514. bool want_client_circ)
  1515. {
  1516. int idx = 0;
  1517. smartlist_t *lst = circuit_get_global_list();
  1518. if (start) {
  1519. idx = TO_CIRCUIT(start)->global_circuitlist_idx + 1;
  1520. }
  1521. for ( ; idx < smartlist_len(lst); ++idx) {
  1522. circuit_t *circ = smartlist_get(lst, idx);
  1523. /* Ignore a marked for close circuit or if the state is not open. */
  1524. if (circ->marked_for_close) {
  1525. continue;
  1526. }
  1527. /* Depending on whether we are looking for client or service circs, skip
  1528. * circuits with other purposes. */
  1529. if (want_client_circ) {
  1530. if (circ->purpose != CIRCUIT_PURPOSE_C_INTRODUCING &&
  1531. circ->purpose != CIRCUIT_PURPOSE_C_INTRODUCE_ACK_WAIT &&
  1532. circ->purpose != CIRCUIT_PURPOSE_C_INTRODUCE_ACKED) {
  1533. continue;
  1534. }
  1535. } else { /* we are looking for service-side circs */
  1536. if (circ->state != CIRCUIT_STATE_OPEN) {
  1537. continue;
  1538. }
  1539. if (circ->purpose != CIRCUIT_PURPOSE_S_ESTABLISH_INTRO &&
  1540. circ->purpose != CIRCUIT_PURPOSE_S_INTRO) {
  1541. continue;
  1542. }
  1543. }
  1544. /* The purposes we are looking for are only for origin circuits so the
  1545. * following is valid. */
  1546. return TO_ORIGIN_CIRCUIT(circ);
  1547. }
  1548. /* Not found. */
  1549. return NULL;
  1550. }
  1551. /** Return the first service rendezvous circuit originating from the global
  1552. * circuit list after <b>start</b> or at the start of the list if <b>start</b>
  1553. * is NULL. Return NULL if no circuit is found.
  1554. *
  1555. * A service rendezvous point circuit has a purpose of either
  1556. * CIRCUIT_PURPOSE_S_CONNECT_REND or CIRCUIT_PURPOSE_S_REND_JOINED. This does
  1557. * not return a circuit marked for close and its state must be open. */
  1558. origin_circuit_t *
  1559. circuit_get_next_service_rp_circ(origin_circuit_t *start)
  1560. {
  1561. int idx = 0;
  1562. smartlist_t *lst = circuit_get_global_list();
  1563. if (start) {
  1564. idx = TO_CIRCUIT(start)->global_circuitlist_idx + 1;
  1565. }
  1566. for ( ; idx < smartlist_len(lst); ++idx) {
  1567. circuit_t *circ = smartlist_get(lst, idx);
  1568. /* Ignore a marked for close circuit or purpose not matching a service
  1569. * intro point or if the state is not open. */
  1570. if (circ->marked_for_close || circ->state != CIRCUIT_STATE_OPEN ||
  1571. (circ->purpose != CIRCUIT_PURPOSE_S_CONNECT_REND &&
  1572. circ->purpose != CIRCUIT_PURPOSE_S_REND_JOINED)) {
  1573. continue;
  1574. }
  1575. /* The purposes we are looking for are only for origin circuits so the
  1576. * following is valid. */
  1577. return TO_ORIGIN_CIRCUIT(circ);
  1578. }
  1579. /* Not found. */
  1580. return NULL;
  1581. }
  1582. /** Return the first circuit originating here in global_circuitlist after
  1583. * <b>start</b> whose purpose is <b>purpose</b>, and where <b>digest</b> (if
  1584. * set) matches the private key digest of the rend data associated with the
  1585. * circuit. Return NULL if no circuit is found. If <b>start</b> is NULL,
  1586. * begin at the start of the list.
  1587. */
  1588. origin_circuit_t *
  1589. circuit_get_next_by_pk_and_purpose(origin_circuit_t *start,
  1590. const uint8_t *digest, uint8_t purpose)
  1591. {
  1592. int idx;
  1593. smartlist_t *lst = circuit_get_global_list();
  1594. tor_assert(CIRCUIT_PURPOSE_IS_ORIGIN(purpose));
  1595. if (start == NULL)
  1596. idx = 0;
  1597. else
  1598. idx = TO_CIRCUIT(start)->global_circuitlist_idx + 1;
  1599. for ( ; idx < smartlist_len(lst); ++idx) {
  1600. circuit_t *circ = smartlist_get(lst, idx);
  1601. origin_circuit_t *ocirc;
  1602. if (circ->marked_for_close)
  1603. continue;
  1604. if (circ->purpose != purpose)
  1605. continue;
  1606. /* At this point we should be able to get a valid origin circuit because
  1607. * the origin purpose we are looking for matches this circuit. */
  1608. if (BUG(!CIRCUIT_PURPOSE_IS_ORIGIN(circ->purpose))) {
  1609. break;
  1610. }
  1611. ocirc = TO_ORIGIN_CIRCUIT(circ);
  1612. if (!digest)
  1613. return ocirc;
  1614. if (rend_circuit_pk_digest_eq(ocirc, digest)) {
  1615. return ocirc;
  1616. }
  1617. }
  1618. return NULL;
  1619. }
  1620. /** We might cannibalize this circuit: Return true if its last hop can be used
  1621. * as a v3 rendezvous point. */
  1622. static int
  1623. circuit_can_be_cannibalized_for_v3_rp(const origin_circuit_t *circ)
  1624. {
  1625. if (!circ->build_state) {
  1626. return 0;
  1627. }
  1628. extend_info_t *chosen_exit = circ->build_state->chosen_exit;
  1629. if (BUG(!chosen_exit)) {
  1630. return 0;
  1631. }
  1632. const node_t *rp_node = node_get_by_id(chosen_exit->identity_digest);
  1633. if (rp_node) {
  1634. if (node_supports_v3_rendezvous_point(rp_node)) {
  1635. return 1;
  1636. }
  1637. }
  1638. return 0;
  1639. }
  1640. /** We are trying to create a circuit of purpose <b>purpose</b> and we are
  1641. * looking for cannibalizable circuits. Return the circuit purpose we would be
  1642. * willing to cannibalize. */
  1643. static uint8_t
  1644. get_circuit_purpose_needed_to_cannibalize(uint8_t purpose)
  1645. {
  1646. if (circuit_should_use_vanguards(purpose)) {
  1647. /* If we are using vanguards, then we should only cannibalize vanguard
  1648. * circuits so that we get the same path construction logic. */
  1649. return CIRCUIT_PURPOSE_HS_VANGUARDS;
  1650. } else {
  1651. /* If no vanguards are used just get a general circuit! */
  1652. return CIRCUIT_PURPOSE_C_GENERAL;
  1653. }
  1654. }
  1655. /** Return a circuit that is open, is CIRCUIT_PURPOSE_C_GENERAL,
  1656. * has a timestamp_dirty value of 0, has flags matching the CIRCLAUNCH_*
  1657. * flags in <b>flags</b>, and if info is defined, does not already use info
  1658. * as any of its hops; or NULL if no circuit fits this description.
  1659. *
  1660. * The <b>purpose</b> argument refers to the purpose of the circuit we want to
  1661. * create, not the purpose of the circuit we want to cannibalize.
  1662. *
  1663. * If !CIRCLAUNCH_NEED_UPTIME, prefer returning non-uptime circuits.
  1664. *
  1665. * To "cannibalize" a circuit means to extend it an extra hop, and use it
  1666. * for some other purpose than we had originally intended. We do this when
  1667. * we want to perform some low-bandwidth task at a specific relay, and we
  1668. * would like the circuit to complete as soon as possible. (If we were going
  1669. * to use a lot of bandwidth, we wouldn't want a circuit with an extra hop.
  1670. * If we didn't care about circuit completion latency, we would just build
  1671. * a new circuit.)
  1672. */
  1673. origin_circuit_t *
  1674. circuit_find_to_cannibalize(uint8_t purpose_to_produce, extend_info_t *info,
  1675. int flags)
  1676. {
  1677. origin_circuit_t *best=NULL;
  1678. int need_uptime = (flags & CIRCLAUNCH_NEED_UPTIME) != 0;
  1679. int need_capacity = (flags & CIRCLAUNCH_NEED_CAPACITY) != 0;
  1680. int internal = (flags & CIRCLAUNCH_IS_INTERNAL) != 0;
  1681. const or_options_t *options = get_options();
  1682. /* We want the circuit we are trying to cannibalize to have this purpose */
  1683. int purpose_to_search_for;
  1684. /* Make sure we're not trying to create a onehop circ by
  1685. * cannibalization. */
  1686. tor_assert(!(flags & CIRCLAUNCH_ONEHOP_TUNNEL));
  1687. purpose_to_search_for = get_circuit_purpose_needed_to_cannibalize(
  1688. purpose_to_produce);
  1689. tor_assert_nonfatal(purpose_to_search_for == CIRCUIT_PURPOSE_C_GENERAL ||
  1690. purpose_to_search_for == CIRCUIT_PURPOSE_HS_VANGUARDS);
  1691. log_debug(LD_CIRC,
  1692. "Hunting for a circ to cannibalize: purpose %d, uptime %d, "
  1693. "capacity %d, internal %d",
  1694. purpose_to_produce, need_uptime, need_capacity, internal);
  1695. SMARTLIST_FOREACH_BEGIN(circuit_get_global_list(), circuit_t *, circ_) {
  1696. if (CIRCUIT_IS_ORIGIN(circ_) &&
  1697. circ_->state == CIRCUIT_STATE_OPEN &&
  1698. !circ_->marked_for_close &&
  1699. circ_->purpose == purpose_to_search_for &&
  1700. !circ_->timestamp_dirty) {
  1701. origin_circuit_t *circ = TO_ORIGIN_CIRCUIT(circ_);
  1702. /* Only cannibalize from reasonable length circuits. If we
  1703. * want C_GENERAL, then only choose 3 hop circs. If we want
  1704. * HS_VANGUARDS, only choose 4 hop circs.
  1705. */
  1706. if (circ->build_state->desired_path_len !=
  1707. route_len_for_purpose(purpose_to_search_for, NULL)) {
  1708. goto next;
  1709. }
  1710. /* Ignore any circuits for which we can't use the Guard. It is possible
  1711. * that the Guard was removed from the samepled set after the circuit
  1712. * was created so avoid using it. */
  1713. if (!entry_guard_could_succeed(circ->guard_state)) {
  1714. goto next;
  1715. }
  1716. if ((!need_uptime || circ->build_state->need_uptime) &&
  1717. (!need_capacity || circ->build_state->need_capacity) &&
  1718. (internal == circ->build_state->is_internal) &&
  1719. !circ->unusable_for_new_conns &&
  1720. circ->remaining_relay_early_cells &&
  1721. !circ->build_state->onehop_tunnel &&
  1722. !circ->isolation_values_set) {
  1723. if (info) {
  1724. /* need to make sure we don't duplicate hops */
  1725. crypt_path_t *hop = circ->cpath;
  1726. const node_t *ri1 = node_get_by_id(info->identity_digest);
  1727. do {
  1728. const node_t *ri2;
  1729. if (tor_memeq(hop->extend_info->identity_digest,
  1730. info->identity_digest, DIGEST_LEN))
  1731. goto next;
  1732. if (ri1 &&
  1733. (ri2 = node_get_by_id(hop->extend_info->identity_digest))
  1734. && nodes_in_same_family(ri1, ri2))
  1735. goto next;
  1736. hop=hop->next;
  1737. } while (hop!=circ->cpath);
  1738. }
  1739. if (options->ExcludeNodes) {
  1740. /* Make sure no existing nodes in the circuit are excluded for
  1741. * general use. (This may be possible if StrictNodes is 0, and we
  1742. * thought we needed to use an otherwise excluded node for, say, a
  1743. * directory operation.) */
  1744. crypt_path_t *hop = circ->cpath;
  1745. do {
  1746. if (routerset_contains_extendinfo(options->ExcludeNodes,
  1747. hop->extend_info))
  1748. goto next;
  1749. hop = hop->next;
  1750. } while (hop != circ->cpath);
  1751. }
  1752. if ((flags & CIRCLAUNCH_IS_V3_RP) &&
  1753. !circuit_can_be_cannibalized_for_v3_rp(circ)) {
  1754. log_debug(LD_GENERAL, "Skipping uncannibalizable circuit for v3 "
  1755. "rendezvous point.");
  1756. goto next;
  1757. }
  1758. if (!best || (best->build_state->need_uptime && !need_uptime))
  1759. best = circ;
  1760. next: ;
  1761. }
  1762. }
  1763. }
  1764. SMARTLIST_FOREACH_END(circ_);
  1765. return best;
  1766. }
  1767. /**
  1768. * Check whether any of the origin circuits that are waiting to see if
  1769. * their guard is good enough to use can be upgraded to "ready". If so,
  1770. * return a new smartlist containing them. Otherwise return NULL.
  1771. */
  1772. smartlist_t *
  1773. circuit_find_circuits_to_upgrade_from_guard_wait(void)
  1774. {
  1775. /* Only if some circuit is actually waiting on an upgrade should we
  1776. * run the algorithm. */
  1777. if (! circuits_pending_other_guards ||
  1778. smartlist_len(circuits_pending_other_guards)==0)
  1779. return NULL;
  1780. /* Only if we have some origin circuits should we run the algorithm. */
  1781. if (!global_origin_circuit_list)
  1782. return NULL;
  1783. /* Okay; we can pass our circuit list to entrynodes.c.*/
  1784. smartlist_t *result = smartlist_new();
  1785. int circuits_upgraded = entry_guards_upgrade_waiting_circuits(
  1786. get_guard_selection_info(),
  1787. global_origin_circuit_list,
  1788. result);
  1789. if (circuits_upgraded && smartlist_len(result)) {
  1790. return result;
  1791. } else {
  1792. smartlist_free(result);
  1793. return NULL;
  1794. }
  1795. }
  1796. /** Return the number of hops in circuit's path. If circ has no entries,
  1797. * or is NULL, returns 0. */
  1798. int
  1799. circuit_get_cpath_len(origin_circuit_t *circ)
  1800. {
  1801. int n = 0;
  1802. if (circ && circ->cpath) {
  1803. crypt_path_t *cpath, *cpath_next = NULL;
  1804. for (cpath = circ->cpath; cpath_next != circ->cpath; cpath = cpath_next) {
  1805. cpath_next = cpath->next;
  1806. ++n;
  1807. }
  1808. }
  1809. return n;
  1810. }
  1811. /** Return the number of opened hops in circuit's path.
  1812. * If circ has no entries, or is NULL, returns 0. */
  1813. int
  1814. circuit_get_cpath_opened_len(const origin_circuit_t *circ)
  1815. {
  1816. int n = 0;
  1817. if (circ && circ->cpath) {
  1818. crypt_path_t *cpath, *cpath_next = NULL;
  1819. for (cpath = circ->cpath;
  1820. cpath->state == CPATH_STATE_OPEN
  1821. && cpath_next != circ->cpath;
  1822. cpath = cpath_next) {
  1823. cpath_next = cpath->next;
  1824. ++n;
  1825. }
  1826. }
  1827. return n;
  1828. }
  1829. /** Return the <b>hopnum</b>th hop in <b>circ</b>->cpath, or NULL if there
  1830. * aren't that many hops in the list. <b>hopnum</b> starts at 1.
  1831. * Returns NULL if <b>hopnum</b> is 0 or negative. */
  1832. crypt_path_t *
  1833. circuit_get_cpath_hop(origin_circuit_t *circ, int hopnum)
  1834. {
  1835. if (circ && circ->cpath && hopnum > 0) {
  1836. crypt_path_t *cpath, *cpath_next = NULL;
  1837. for (cpath = circ->cpath; cpath_next != circ->cpath; cpath = cpath_next) {
  1838. cpath_next = cpath->next;
  1839. if (--hopnum <= 0)
  1840. return cpath;
  1841. }
  1842. }
  1843. return NULL;
  1844. }
  1845. /** Go through the circuitlist; mark-for-close each circuit that starts
  1846. * at us but has not yet been used. */
  1847. void
  1848. circuit_mark_all_unused_circs(void)
  1849. {
  1850. SMARTLIST_FOREACH_BEGIN(circuit_get_global_list(), circuit_t *, circ) {
  1851. if (CIRCUIT_IS_ORIGIN(circ) &&
  1852. !circ->marked_for_close &&
  1853. !circ->timestamp_dirty)
  1854. circuit_mark_for_close(circ, END_CIRC_REASON_FINISHED);
  1855. }
  1856. SMARTLIST_FOREACH_END(circ);
  1857. }
  1858. /** Go through the circuitlist; for each circuit that starts at us
  1859. * and is dirty, frob its timestamp_dirty so we won't use it for any
  1860. * new streams.
  1861. *
  1862. * This is useful for letting the user change pseudonyms, so new
  1863. * streams will not be linkable to old streams.
  1864. */
  1865. void
  1866. circuit_mark_all_dirty_circs_as_unusable(void)
  1867. {
  1868. SMARTLIST_FOREACH_BEGIN(circuit_get_global_list(), circuit_t *, circ) {
  1869. if (CIRCUIT_IS_ORIGIN(circ) &&
  1870. !circ->marked_for_close &&
  1871. circ->timestamp_dirty) {
  1872. mark_circuit_unusable_for_new_conns(TO_ORIGIN_CIRCUIT(circ));
  1873. }
  1874. }
  1875. SMARTLIST_FOREACH_END(circ);
  1876. }
  1877. /**
  1878. * Report any queued cells on or_circuits as written in our bandwidth
  1879. * totals, for the specified channel direction.
  1880. *
  1881. * When we close a circuit or clear its cell queues, we've read
  1882. * data and recorded those bytes in our read statistics, but we're
  1883. * not going to write it. This discrepancy can be used by an adversary
  1884. * to infer information from our public relay statistics and perform
  1885. * attacks such as guard discovery.
  1886. *
  1887. * This function is in the critical path of circuit_mark_for_close().
  1888. * It must be (and is) O(1)!
  1889. *
  1890. * See https://trac.torproject.org/projects/tor/ticket/23512.
  1891. */
  1892. void
  1893. circuit_synchronize_written_or_bandwidth(const circuit_t *c,
  1894. circuit_channel_direction_t dir)
  1895. {
  1896. uint64_t cells;
  1897. uint64_t cell_size;
  1898. uint64_t written_sync;
  1899. const channel_t *chan = NULL;
  1900. const or_circuit_t *or_circ;
  1901. if (!CIRCUIT_IS_ORCIRC(c))
  1902. return;
  1903. or_circ = CONST_TO_OR_CIRCUIT(c);
  1904. if (dir == CIRCUIT_N_CHAN) {
  1905. chan = c->n_chan;
  1906. cells = c->n_chan_cells.n;
  1907. } else {
  1908. chan = or_circ->p_chan;
  1909. cells = or_circ->p_chan_cells.n;
  1910. }
  1911. /* If we still know the chan, determine real cell size. Otherwise,
  1912. * assume it's a wide circid channel */
  1913. if (chan)
  1914. cell_size = get_cell_network_size(chan->wide_circ_ids);
  1915. else
  1916. cell_size = CELL_MAX_NETWORK_SIZE;
  1917. /* The missing written bytes are the cell counts times their cell
  1918. * size plus TLS per cell overhead */
  1919. written_sync = cells*(cell_size+TLS_PER_CELL_OVERHEAD);
  1920. /* Report the missing bytes as written, to avoid asymmetry.
  1921. * We must use time() for consistency with rephist, even though on
  1922. * some very old rare platforms, approx_time() may be faster. */
  1923. rep_hist_note_bytes_written(written_sync, time(NULL));
  1924. }
  1925. /** Mark <b>circ</b> to be closed next time we call
  1926. * circuit_close_all_marked(). Do any cleanup needed:
  1927. * - If state is onionskin_pending, remove circ from the onion_pending
  1928. * list.
  1929. * - If circ isn't open yet: call circuit_build_failed() if we're
  1930. * the origin.
  1931. * - If purpose is C_INTRODUCE_ACK_WAIT, report the intro point
  1932. * failure we just had to the hidden service client module.
  1933. * - If purpose is C_INTRODUCING and <b>reason</b> isn't TIMEOUT,
  1934. * report to the hidden service client module that the intro point
  1935. * we just tried may be unreachable.
  1936. * - Send appropriate destroys and edge_destroys for conns and
  1937. * streams attached to circ.
  1938. * - If circ->rend_splice is set (we are the midpoint of a joined
  1939. * rendezvous stream), then mark the other circuit to close as well.
  1940. */
  1941. MOCK_IMPL(void,
  1942. circuit_mark_for_close_, (circuit_t *circ, int reason, int line,
  1943. const char *file))
  1944. {
  1945. int orig_reason = reason; /* Passed to the controller */
  1946. assert_circuit_ok(circ);
  1947. tor_assert(line);
  1948. tor_assert(file);
  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 (circ->n_mux)
  2160. circuitmux_clear_num_cells(circ->n_mux, circ);
  2161. if (! CIRCUIT_IS_ORIGIN(circ)) {
  2162. or_circuit_t *orcirc = TO_OR_CIRCUIT(circ);
  2163. cell_queue_clear(&orcirc->p_chan_cells);
  2164. if (orcirc->p_mux)
  2165. circuitmux_clear_num_cells(orcirc->p_mux, circ);
  2166. }
  2167. }
  2168. static size_t
  2169. single_conn_free_bytes(connection_t *conn)
  2170. {
  2171. size_t result = 0;
  2172. if (conn->inbuf) {
  2173. result += buf_allocation(conn->inbuf);
  2174. buf_clear(conn->inbuf);
  2175. }
  2176. if (conn->outbuf) {
  2177. result += buf_allocation(conn->outbuf);
  2178. buf_clear(conn->outbuf);
  2179. conn->outbuf_flushlen = 0;
  2180. }
  2181. if (conn->type == CONN_TYPE_DIR) {
  2182. dir_connection_t *dir_conn = TO_DIR_CONN(conn);
  2183. if (dir_conn->compress_state) {
  2184. result += tor_compress_state_size(dir_conn->compress_state);
  2185. tor_compress_free(dir_conn->compress_state);
  2186. dir_conn->compress_state = NULL;
  2187. }
  2188. }
  2189. return result;
  2190. }
  2191. /** Aggressively free buffer contents on all the buffers of all streams in the
  2192. * list starting at <b>stream</b>. Return the number of bytes recovered. */
  2193. static size_t
  2194. marked_circuit_streams_free_bytes(edge_connection_t *stream)
  2195. {
  2196. size_t result = 0;
  2197. for ( ; stream; stream = stream->next_stream) {
  2198. connection_t *conn = TO_CONN(stream);
  2199. result += single_conn_free_bytes(conn);
  2200. if (conn->linked_conn) {
  2201. result += single_conn_free_bytes(conn->linked_conn);
  2202. }
  2203. }
  2204. return result;
  2205. }
  2206. /** Aggressively free buffer contents on all the buffers of all streams on
  2207. * circuit <b>c</b>. Return the number of bytes recovered. */
  2208. static size_t
  2209. marked_circuit_free_stream_bytes(circuit_t *c)
  2210. {
  2211. if (CIRCUIT_IS_ORIGIN(c)) {
  2212. return marked_circuit_streams_free_bytes(TO_ORIGIN_CIRCUIT(c)->p_streams);
  2213. } else {
  2214. return marked_circuit_streams_free_bytes(TO_OR_CIRCUIT(c)->n_streams);
  2215. }
  2216. }
  2217. /** Return the number of cells used by the circuit <b>c</b>'s cell queues. */
  2218. STATIC size_t
  2219. n_cells_in_circ_queues(const circuit_t *c)
  2220. {
  2221. size_t n = c->n_chan_cells.n;
  2222. if (! CIRCUIT_IS_ORIGIN(c)) {
  2223. circuit_t *cc = (circuit_t *) c;
  2224. n += TO_OR_CIRCUIT(cc)->p_chan_cells.n;
  2225. }
  2226. return n;
  2227. }
  2228. /** Return the number of bytes allocated for <b>c</b>'s half-open streams. */
  2229. static size_t
  2230. circuit_alloc_in_half_streams(const circuit_t *c)
  2231. {
  2232. if (! CIRCUIT_IS_ORIGIN(c)) {
  2233. return 0;
  2234. }
  2235. const origin_circuit_t *ocirc = CONST_TO_ORIGIN_CIRCUIT(c);
  2236. if (ocirc->half_streams)
  2237. return smartlist_len(ocirc->half_streams) * sizeof(half_edge_t);
  2238. else
  2239. return 0;
  2240. }
  2241. /**
  2242. * Return the age of the oldest cell queued on <b>c</b>, in timestamp units.
  2243. * Return 0 if there are no cells queued on c. Requires that <b>now</b> be
  2244. * the current coarse timestamp.
  2245. *
  2246. * This function will return incorrect results if the oldest cell queued on
  2247. * the circuit is older than about 2**32 msec (about 49 days) old.
  2248. */
  2249. STATIC uint32_t
  2250. circuit_max_queued_cell_age(const circuit_t *c, uint32_t now)
  2251. {
  2252. uint32_t age = 0;
  2253. packed_cell_t *cell;
  2254. if (NULL != (cell = TOR_SIMPLEQ_FIRST(&c->n_chan_cells.head)))
  2255. age = now - cell->inserted_timestamp;
  2256. if (! CIRCUIT_IS_ORIGIN(c)) {
  2257. const or_circuit_t *orcirc = CONST_TO_OR_CIRCUIT(c);
  2258. if (NULL != (cell = TOR_SIMPLEQ_FIRST(&orcirc->p_chan_cells.head))) {
  2259. uint32_t age2 = now - cell->inserted_timestamp;
  2260. if (age2 > age)
  2261. return age2;
  2262. }
  2263. }
  2264. return age;
  2265. }
  2266. /** Return the age of the oldest buffer chunk on <b>conn</b>, where age is
  2267. * taken in timestamp units before the time <b>now</b>. If the connection has
  2268. * no data, treat it as having age zero.
  2269. **/
  2270. static uint32_t
  2271. conn_get_buffer_age(const connection_t *conn, uint32_t now_ts)
  2272. {
  2273. uint32_t age = 0, age2;
  2274. if (conn->outbuf) {
  2275. age2 = buf_get_oldest_chunk_timestamp(conn->outbuf, now_ts);
  2276. if (age2 > age)
  2277. age = age2;
  2278. }
  2279. if (conn->inbuf) {
  2280. age2 = buf_get_oldest_chunk_timestamp(conn->inbuf, now_ts);
  2281. if (age2 > age)
  2282. age = age2;
  2283. }
  2284. return age;
  2285. }
  2286. /** Return the age in timestamp units of the oldest buffer chunk on any stream
  2287. * in the linked list <b>stream</b>, where age is taken in timestamp units
  2288. * before the timestamp <b>now</b>. */
  2289. static uint32_t
  2290. circuit_get_streams_max_data_age(const edge_connection_t *stream, uint32_t now)
  2291. {
  2292. uint32_t age = 0, age2;
  2293. for (; stream; stream = stream->next_stream) {
  2294. const connection_t *conn = TO_CONN(stream);
  2295. age2 = conn_get_buffer_age(conn, now);
  2296. if (age2 > age)
  2297. age = age2;
  2298. if (conn->linked_conn) {
  2299. age2 = conn_get_buffer_age(conn->linked_conn, now);
  2300. if (age2 > age)
  2301. age = age2;
  2302. }
  2303. }
  2304. return age;
  2305. }
  2306. /** Return the age in timestamp units of the oldest buffer chunk on any stream
  2307. * attached to the circuit <b>c</b>, where age is taken before the timestamp
  2308. * <b>now</b>. */
  2309. STATIC uint32_t
  2310. circuit_max_queued_data_age(const circuit_t *c, uint32_t now)
  2311. {
  2312. if (CIRCUIT_IS_ORIGIN(c)) {
  2313. return circuit_get_streams_max_data_age(
  2314. CONST_TO_ORIGIN_CIRCUIT(c)->p_streams, now);
  2315. } else {
  2316. return circuit_get_streams_max_data_age(
  2317. CONST_TO_OR_CIRCUIT(c)->n_streams, now);
  2318. }
  2319. }
  2320. /** Return the age of the oldest cell or stream buffer chunk on the circuit
  2321. * <b>c</b>, where age is taken in timestamp units before the timestamp
  2322. * <b>now</b> */
  2323. STATIC uint32_t
  2324. circuit_max_queued_item_age(const circuit_t *c, uint32_t now)
  2325. {
  2326. uint32_t cell_age = circuit_max_queued_cell_age(c, now);
  2327. uint32_t data_age = circuit_max_queued_data_age(c, now);
  2328. if (cell_age > data_age)
  2329. return cell_age;
  2330. else
  2331. return data_age;
  2332. }
  2333. /** Helper to sort a list of circuit_t by age of oldest item, in descending
  2334. * order. */
  2335. static int
  2336. circuits_compare_by_oldest_queued_item_(const void **a_, const void **b_)
  2337. {
  2338. const circuit_t *a = *a_;
  2339. const circuit_t *b = *b_;
  2340. uint32_t age_a = a->age_tmp;
  2341. uint32_t age_b = b->age_tmp;
  2342. if (age_a < age_b)
  2343. return 1;
  2344. else if (age_a == age_b)
  2345. return 0;
  2346. else
  2347. return -1;
  2348. }
  2349. static uint32_t now_ts_for_buf_cmp;
  2350. /** Helper to sort a list of circuit_t by age of oldest item, in descending
  2351. * order. */
  2352. static int
  2353. conns_compare_by_buffer_age_(const void **a_, const void **b_)
  2354. {
  2355. const connection_t *a = *a_;
  2356. const connection_t *b = *b_;
  2357. time_t age_a = conn_get_buffer_age(a, now_ts_for_buf_cmp);
  2358. time_t age_b = conn_get_buffer_age(b, now_ts_for_buf_cmp);
  2359. if (age_a < age_b)
  2360. return 1;
  2361. else if (age_a == age_b)
  2362. return 0;
  2363. else
  2364. return -1;
  2365. }
  2366. #define FRACTION_OF_DATA_TO_RETAIN_ON_OOM 0.90
  2367. /** We're out of memory for cells, having allocated <b>current_allocation</b>
  2368. * bytes' worth. Kill the 'worst' circuits until we're under
  2369. * FRACTION_OF_DATA_TO_RETAIN_ON_OOM of our maximum usage. */
  2370. void
  2371. circuits_handle_oom(size_t current_allocation)
  2372. {
  2373. smartlist_t *circlist;
  2374. smartlist_t *connection_array = get_connection_array();
  2375. int conn_idx;
  2376. size_t mem_to_recover;
  2377. size_t mem_recovered=0;
  2378. int n_circuits_killed=0;
  2379. int n_dirconns_killed=0;
  2380. uint32_t now_ts;
  2381. log_notice(LD_GENERAL, "We're low on memory (cell queues total alloc:"
  2382. " %"TOR_PRIuSZ" buffer total alloc: %" TOR_PRIuSZ ","
  2383. " tor compress total alloc: %" TOR_PRIuSZ
  2384. " (zlib: %" TOR_PRIuSZ ", zstd: %" TOR_PRIuSZ ","
  2385. " lzma: %" TOR_PRIuSZ "),"
  2386. " rendezvous cache total alloc: %" TOR_PRIuSZ "). Killing"
  2387. " circuits withover-long queues. (This behavior is controlled by"
  2388. " MaxMemInQueues.)",
  2389. cell_queues_get_total_allocation(),
  2390. buf_get_total_allocation(),
  2391. tor_compress_get_total_allocation(),
  2392. tor_zlib_get_total_allocation(),
  2393. tor_zstd_get_total_allocation(),
  2394. tor_lzma_get_total_allocation(),
  2395. rend_cache_get_total_allocation());
  2396. {
  2397. size_t mem_target = (size_t)(get_options()->MaxMemInQueues *
  2398. FRACTION_OF_DATA_TO_RETAIN_ON_OOM);
  2399. if (current_allocation <= mem_target)
  2400. return;
  2401. mem_to_recover = current_allocation - mem_target;
  2402. }
  2403. now_ts = monotime_coarse_get_stamp();
  2404. circlist = circuit_get_global_list();
  2405. SMARTLIST_FOREACH_BEGIN(circlist, circuit_t *, circ) {
  2406. circ->age_tmp = circuit_max_queued_item_age(circ, now_ts);
  2407. } SMARTLIST_FOREACH_END(circ);
  2408. /* This is O(n log n); there are faster algorithms we could use instead.
  2409. * Let's hope this doesn't happen enough to be in the critical path. */
  2410. smartlist_sort(circlist, circuits_compare_by_oldest_queued_item_);
  2411. /* Fix up the indices before we run into trouble */
  2412. SMARTLIST_FOREACH_BEGIN(circlist, circuit_t *, circ) {
  2413. circ->global_circuitlist_idx = circ_sl_idx;
  2414. } SMARTLIST_FOREACH_END(circ);
  2415. /* Now sort the connection array ... */
  2416. now_ts_for_buf_cmp = now_ts;
  2417. smartlist_sort(connection_array, conns_compare_by_buffer_age_);
  2418. now_ts_for_buf_cmp = 0;
  2419. /* Fix up the connection array to its new order. */
  2420. SMARTLIST_FOREACH_BEGIN(connection_array, connection_t *, conn) {
  2421. conn->conn_array_index = conn_sl_idx;
  2422. } SMARTLIST_FOREACH_END(conn);
  2423. /* Okay, now the worst circuits and connections are at the front of their
  2424. * respective lists. Let's mark them, and reclaim their storage
  2425. * aggressively. */
  2426. conn_idx = 0;
  2427. SMARTLIST_FOREACH_BEGIN(circlist, circuit_t *, circ) {
  2428. size_t n;
  2429. size_t freed;
  2430. /* Free storage in any non-linked directory connections that have buffered
  2431. * data older than this circuit. */
  2432. while (conn_idx < smartlist_len(connection_array)) {
  2433. connection_t *conn = smartlist_get(connection_array, conn_idx);
  2434. uint32_t conn_age = conn_get_buffer_age(conn, now_ts);
  2435. if (conn_age < circ->age_tmp) {
  2436. break;
  2437. }
  2438. if (conn->type == CONN_TYPE_DIR && conn->linked_conn == NULL) {
  2439. if (!conn->marked_for_close)
  2440. connection_mark_for_close(conn);
  2441. mem_recovered += single_conn_free_bytes(conn);
  2442. ++n_dirconns_killed;
  2443. if (mem_recovered >= mem_to_recover)
  2444. goto done_recovering_mem;
  2445. }
  2446. ++conn_idx;
  2447. }
  2448. /* Now, kill the circuit. */
  2449. n = n_cells_in_circ_queues(circ);
  2450. const size_t half_stream_alloc = circuit_alloc_in_half_streams(circ);
  2451. if (! circ->marked_for_close) {
  2452. circuit_mark_for_close(circ, END_CIRC_REASON_RESOURCELIMIT);
  2453. }
  2454. marked_circuit_free_cells(circ);
  2455. freed = marked_circuit_free_stream_bytes(circ);
  2456. ++n_circuits_killed;
  2457. mem_recovered += n * packed_cell_mem_cost();
  2458. mem_recovered += half_stream_alloc;
  2459. mem_recovered += freed;
  2460. if (mem_recovered >= mem_to_recover)
  2461. goto done_recovering_mem;
  2462. } SMARTLIST_FOREACH_END(circ);
  2463. done_recovering_mem:
  2464. log_notice(LD_GENERAL, "Removed %"TOR_PRIuSZ" bytes by killing %d circuits; "
  2465. "%d circuits remain alive. Also killed %d non-linked directory "
  2466. "connections.",
  2467. mem_recovered,
  2468. n_circuits_killed,
  2469. smartlist_len(circlist) - n_circuits_killed,
  2470. n_dirconns_killed);
  2471. }
  2472. /** Verify that cpath layer <b>cp</b> has all of its invariants
  2473. * correct. Trigger an assert if anything is invalid.
  2474. */
  2475. void
  2476. assert_cpath_layer_ok(const crypt_path_t *cp)
  2477. {
  2478. // tor_assert(cp->addr); /* these are zero for rendezvous extra-hops */
  2479. // tor_assert(cp->port);
  2480. tor_assert(cp);
  2481. tor_assert(cp->magic == CRYPT_PATH_MAGIC);
  2482. switch (cp->state)
  2483. {
  2484. case CPATH_STATE_OPEN:
  2485. relay_crypto_assert_ok(&cp->crypto);
  2486. /* fall through */
  2487. case CPATH_STATE_CLOSED:
  2488. /*XXXX Assert that there's no handshake_state either. */
  2489. tor_assert(!cp->rend_dh_handshake_state);
  2490. break;
  2491. case CPATH_STATE_AWAITING_KEYS:
  2492. /* tor_assert(cp->dh_handshake_state); */
  2493. break;
  2494. default:
  2495. log_fn(LOG_ERR, LD_BUG, "Unexpected state %d", cp->state);
  2496. tor_assert(0);
  2497. }
  2498. tor_assert(cp->package_window >= 0);
  2499. tor_assert(cp->deliver_window >= 0);
  2500. }
  2501. /** Verify that cpath <b>cp</b> has all of its invariants
  2502. * correct. Trigger an assert if anything is invalid.
  2503. */
  2504. static void
  2505. assert_cpath_ok(const crypt_path_t *cp)
  2506. {
  2507. const crypt_path_t *start = cp;
  2508. do {
  2509. assert_cpath_layer_ok(cp);
  2510. /* layers must be in sequence of: "open* awaiting? closed*" */
  2511. if (cp != start) {
  2512. if (cp->state == CPATH_STATE_AWAITING_KEYS) {
  2513. tor_assert(cp->prev->state == CPATH_STATE_OPEN);
  2514. } else if (cp->state == CPATH_STATE_OPEN) {
  2515. tor_assert(cp->prev->state == CPATH_STATE_OPEN);
  2516. }
  2517. }
  2518. cp = cp->next;
  2519. tor_assert(cp);
  2520. } while (cp != start);
  2521. }
  2522. /** Verify that circuit <b>c</b> has all of its invariants
  2523. * correct. Trigger an assert if anything is invalid.
  2524. */
  2525. MOCK_IMPL(void,
  2526. assert_circuit_ok,(const circuit_t *c))
  2527. {
  2528. edge_connection_t *conn;
  2529. const or_circuit_t *or_circ = NULL;
  2530. const origin_circuit_t *origin_circ = NULL;
  2531. tor_assert(c);
  2532. tor_assert(c->magic == ORIGIN_CIRCUIT_MAGIC || c->magic == OR_CIRCUIT_MAGIC);
  2533. tor_assert(c->purpose >= CIRCUIT_PURPOSE_MIN_ &&
  2534. c->purpose <= CIRCUIT_PURPOSE_MAX_);
  2535. if (CIRCUIT_IS_ORIGIN(c))
  2536. origin_circ = CONST_TO_ORIGIN_CIRCUIT(c);
  2537. else
  2538. or_circ = CONST_TO_OR_CIRCUIT(c);
  2539. if (c->n_chan) {
  2540. tor_assert(!c->n_hop);
  2541. if (c->n_circ_id) {
  2542. /* We use the _impl variant here to make sure we don't fail on marked
  2543. * circuits, which would not be returned by the regular function. */
  2544. circuit_t *c2 = circuit_get_by_circid_channel_impl(c->n_circ_id,
  2545. c->n_chan, NULL);
  2546. tor_assert(c == c2);
  2547. }
  2548. }
  2549. if (or_circ && or_circ->p_chan) {
  2550. if (or_circ->p_circ_id) {
  2551. /* ibid */
  2552. circuit_t *c2 =
  2553. circuit_get_by_circid_channel_impl(or_circ->p_circ_id,
  2554. or_circ->p_chan, NULL);
  2555. tor_assert(c == c2);
  2556. }
  2557. }
  2558. if (or_circ)
  2559. for (conn = or_circ->n_streams; conn; conn = conn->next_stream)
  2560. tor_assert(conn->base_.type == CONN_TYPE_EXIT);
  2561. tor_assert(c->deliver_window >= 0);
  2562. tor_assert(c->package_window >= 0);
  2563. if (c->state == CIRCUIT_STATE_OPEN ||
  2564. c->state == CIRCUIT_STATE_GUARD_WAIT) {
  2565. tor_assert(!c->n_chan_create_cell);
  2566. if (or_circ) {
  2567. relay_crypto_assert_ok(&or_circ->crypto);
  2568. }
  2569. }
  2570. if (c->state == CIRCUIT_STATE_CHAN_WAIT && !c->marked_for_close) {
  2571. tor_assert(circuits_pending_chans &&
  2572. smartlist_contains(circuits_pending_chans, c));
  2573. } else {
  2574. tor_assert(!circuits_pending_chans ||
  2575. !smartlist_contains(circuits_pending_chans, c));
  2576. }
  2577. if (origin_circ && origin_circ->cpath) {
  2578. assert_cpath_ok(origin_circ->cpath);
  2579. }
  2580. if (c->purpose == CIRCUIT_PURPOSE_REND_ESTABLISHED) {
  2581. tor_assert(or_circ);
  2582. if (!c->marked_for_close) {
  2583. tor_assert(or_circ->rend_splice);
  2584. tor_assert(or_circ->rend_splice->rend_splice == or_circ);
  2585. }
  2586. tor_assert(or_circ->rend_splice != or_circ);
  2587. } else {
  2588. tor_assert(!or_circ || !or_circ->rend_splice);
  2589. }
  2590. }