circuitlist.c 58 KB

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