circuitlist.c 77 KB

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