circuitlist.c 60 KB

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