circuitlist.c 68 KB

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