circuitlist.c 77 KB

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