circuitlist.c 74 KB

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