circuitlist.c 71 KB

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