circuitlist.c 67 KB

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