circuitlist.c 85 KB

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