circuitlist.c 67 KB

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