circuitlist.c 88 KB

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