circuitlist.c 74 KB

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