circuitlist.c 79 KB

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