circuitlist.c 82 KB

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