circuitlist.c 88 KB

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