circuitlist.c 88 KB

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