circuitlist.c 67 KB

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