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