local_fs.rs 72 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888
  1. // SPDX-License-Identifier: AGPL-3.0-or-later
  2. use crate::{msg::*, server::FsProvider};
  3. use btlib::{
  4. accessor::Accessor,
  5. bterr,
  6. crypto::{rand_vec, Creds, Decrypter, HashKind, Signer, SymKey},
  7. error::BtErr,
  8. AuthzAttrs, BlockAccessor, BlockError, BlockMeta, BlockMetaSecrets, BlockOpenOptions,
  9. BlockPath, BlockReader, DirEntry, Directory, Epoch, FileBlock, FlushMeta, IssuedProcRec,
  10. MetaAccess, MetaReader, Positioned, Principal, Principaled, ProcRec, Result, Split, TrySeek,
  11. ZeroExtendable,
  12. };
  13. use btserde::{read_from, write_to};
  14. use core::future::Ready;
  15. use log::{debug, error, warn};
  16. use positioned_io::{ReadAt, Size};
  17. use serde::{Deserialize, Serialize};
  18. use std::{
  19. collections::hash_map::{self, HashMap},
  20. fmt::{Display, Formatter},
  21. fs::File,
  22. future::Future,
  23. io::{self, Seek, SeekFrom, Write as IoWrite},
  24. net::{IpAddr, Ipv6Addr},
  25. ops::{Deref, DerefMut},
  26. path::{Path, PathBuf},
  27. sync::{
  28. atomic::{AtomicU64, Ordering},
  29. Arc,
  30. },
  31. time::Duration,
  32. };
  33. use tokio::sync::{
  34. Mutex, MutexGuard, OwnedMutexGuard, OwnedRwLockReadGuard, RwLock, RwLockReadGuard,
  35. RwLockWriteGuard,
  36. };
  37. use zeroize::ZeroizeOnDrop;
  38. pub use private::{Authorizer, AuthzContext, Error, LocalFs, ModeAuthorizer};
  39. mod private {
  40. use super::*;
  41. type Inode = u64;
  42. type Handle = u64;
  43. #[derive(Debug, Clone, PartialEq, Eq, Hash, Serialize, Deserialize)]
  44. pub enum Error {
  45. NotOpen(Inode),
  46. InvalidHandle { inode: Inode, handle: Handle },
  47. NoHandlesAvailable(Inode),
  48. InodeNotFound(Inode),
  49. ReadOnlyHandle(Handle),
  50. WrongOwner,
  51. }
  52. impl Display for Error {
  53. fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
  54. match self {
  55. Error::NotOpen(inode) => write!(f, "inode {inode} is not open"),
  56. Error::InvalidHandle { inode, handle } => {
  57. write!(f, "invalid handle {handle} for inode {inode}")
  58. }
  59. Error::NoHandlesAvailable(inode) => {
  60. write!(f, "no handles are available for inode {inode}")
  61. }
  62. Error::InodeNotFound(inode) => write!(f, "inode {inode} could not be found"),
  63. Error::ReadOnlyHandle(handle) => {
  64. write!(f, "cannot mutably access read-only handle {handle}")
  65. }
  66. Error::WrongOwner => write!(f, "handle is not owned by the requestor"),
  67. }
  68. }
  69. }
  70. trait BlockPathExt {
  71. fn assert_eq(&self, other: &BlockPath) -> Result<()>;
  72. }
  73. impl BlockPathExt for BlockPath {
  74. fn assert_eq(&self, other: &BlockPath) -> Result<()> {
  75. if self != other {
  76. Err(Error::WrongOwner.into())
  77. } else {
  78. Ok(())
  79. }
  80. }
  81. }
  82. impl std::error::Error for Error {}
  83. /// This type provides context for an authorization decision as to whether a given process will
  84. /// be allowed to access a block.
  85. pub struct AuthzContext<'a> {
  86. /// The path from which this request was received.
  87. pub from: &'a BlockPath,
  88. /// The attributes of the principal whose access is being authorized.
  89. pub attrs: &'a AuthzAttrs,
  90. /// A reference to the metadata of a block, the access to which is being authorized.
  91. pub meta: &'a BlockMeta,
  92. }
  93. impl<'a> AuthzContext<'a> {
  94. fn new(from: &'a BlockPath, attrs: &'a AuthzAttrs, meta: &'a BlockMeta) -> Self {
  95. Self { from, attrs, meta }
  96. }
  97. }
  98. /// A trait for types which can render authorization decisions.
  99. pub trait Authorizer {
  100. /// Returns [Ok] if read authorization is granted, and [Err] otherwise.
  101. fn can_read(&self, ctx: &AuthzContext<'_>) -> io::Result<()>;
  102. /// Returns [Ok] if write authorization is granted, and [Err] otherwise.
  103. fn can_write(&self, ctx: &AuthzContext<'_>) -> io::Result<()>;
  104. /// Returns [Ok] if execute authorization is granted, and [Err] otherwise.
  105. fn can_exec(&self, ctx: &AuthzContext<'_>) -> io::Result<()>;
  106. }
  107. /// A particularly simple authorizer that just looks at the mode bits in the block metadata
  108. /// to make authorization decisions.
  109. pub struct ModeAuthorizer;
  110. impl ModeAuthorizer {
  111. fn authorize(mode: u32, mask: u32, denied_msg: &str) -> io::Result<()> {
  112. if (mode & mask) != 0 {
  113. Ok(())
  114. } else {
  115. Err(io::Error::new(io::ErrorKind::PermissionDenied, denied_msg))
  116. }
  117. }
  118. fn user_is_root(ctx: &AuthzContext<'_>) -> bool {
  119. ctx.attrs.uid == 0
  120. }
  121. }
  122. impl Authorizer for ModeAuthorizer {
  123. fn can_read(&self, ctx: &AuthzContext<'_>) -> io::Result<()> {
  124. if Self::user_is_root(ctx) {
  125. return Ok(());
  126. }
  127. let secrets = ctx.meta.body().secrets()?;
  128. let mask = (libc::S_IRUSR * (secrets.uid == ctx.attrs.uid) as u32)
  129. | (libc::S_IRGRP * (secrets.gid == ctx.attrs.gid) as u32)
  130. | libc::S_IROTH;
  131. Self::authorize(secrets.mode, mask, "read access denied")
  132. }
  133. fn can_write(&self, ctx: &AuthzContext<'_>) -> io::Result<()> {
  134. if Self::user_is_root(ctx) {
  135. return Ok(());
  136. }
  137. let secrets = ctx.meta.body().secrets()?;
  138. let mask = (libc::S_IWUSR * (secrets.uid == ctx.attrs.uid) as u32)
  139. | (libc::S_IWGRP * (secrets.gid == ctx.attrs.gid) as u32)
  140. | libc::S_IWOTH;
  141. Self::authorize(secrets.mode, mask, "write access denied")
  142. }
  143. fn can_exec(&self, ctx: &AuthzContext<'_>) -> io::Result<()> {
  144. if Self::user_is_root(ctx) {
  145. return Ok(());
  146. }
  147. let secrets = ctx.meta.body().secrets()?;
  148. let mask = (libc::S_IXUSR * (secrets.uid == ctx.attrs.uid) as u32)
  149. | (libc::S_IXGRP * (secrets.gid == ctx.attrs.gid) as u32)
  150. | libc::S_IXOTH;
  151. Self::authorize(secrets.mode, mask, "exec access denied")
  152. }
  153. }
  154. type EmptyAccessor = Option<Accessor<&'static [u8]>>;
  155. type HandleValueParts<'a> = (&'a Arc<Mutex<EmptyAccessor>>, &'a Arc<BlockPath>, Flags);
  156. struct HandleGuard<B: Size, G: DerefMut<Target = EmptyAccessor>> {
  157. guard: G,
  158. accessor: Option<Accessor<B>>,
  159. flags: Flags,
  160. }
  161. impl<B: Size, G: DerefMut<Target = EmptyAccessor>> HandleGuard<B, G> {
  162. fn new(flags: Flags, mut guard: G, block: B) -> Self {
  163. let accessor = guard
  164. .take()
  165. .map(move |accessor| Accessor::combine(accessor, block));
  166. Self {
  167. guard,
  168. accessor,
  169. flags,
  170. }
  171. }
  172. }
  173. impl<B: Size, G: DerefMut<Target = EmptyAccessor>> Drop for HandleGuard<B, G> {
  174. fn drop(&mut self) {
  175. *self.guard = self.accessor.take().map(|accessor| {
  176. let (accessor, _) = accessor.split();
  177. accessor
  178. });
  179. }
  180. }
  181. impl<B: Size, G: DerefMut<Target = EmptyAccessor>> Deref for HandleGuard<B, G> {
  182. type Target = Accessor<B>;
  183. fn deref(&self) -> &Self::Target {
  184. self.accessor.as_ref().unwrap()
  185. }
  186. }
  187. impl<B: Size, G: DerefMut<Target = EmptyAccessor>> DerefMut for HandleGuard<B, G> {
  188. fn deref_mut(&mut self) -> &mut Self::Target {
  189. self.accessor.as_mut().unwrap()
  190. }
  191. }
  192. enum HandleValue {
  193. File {
  194. accessor: Arc<Mutex<EmptyAccessor>>,
  195. owner: Arc<BlockPath>,
  196. flags: Flags,
  197. },
  198. Directory {
  199. accessor: Arc<Mutex<EmptyAccessor>>,
  200. owner: Arc<BlockPath>,
  201. flags: Flags,
  202. dir: Directory,
  203. },
  204. }
  205. impl HandleValue {
  206. fn new<T: Size>(accessor: Accessor<T>, owner: Arc<BlockPath>, flags: Flags) -> HandleValue {
  207. let (accessor, ..) = accessor.split();
  208. HandleValue::File {
  209. accessor: Arc::new(Mutex::new(Some(accessor))),
  210. owner,
  211. flags,
  212. }
  213. }
  214. fn flags(&self) -> Flags {
  215. match self {
  216. Self::File { flags, .. } => *flags,
  217. Self::Directory { flags, .. } => *flags,
  218. }
  219. }
  220. fn parts(&self) -> HandleValueParts<'_> {
  221. match self {
  222. Self::File {
  223. accessor,
  224. owner,
  225. flags,
  226. } => (accessor, owner, *flags),
  227. Self::Directory {
  228. accessor,
  229. owner,
  230. flags,
  231. ..
  232. } => (accessor, owner, *flags),
  233. }
  234. }
  235. fn convert_to_dir<C: Signer + Principaled + Decrypter>(
  236. self,
  237. block: &mut FileBlock<C>,
  238. ) -> Result<HandleValue> {
  239. let (accessor, owner, flags) = match self {
  240. Self::File {
  241. accessor,
  242. owner,
  243. flags,
  244. } => (accessor, owner, flags),
  245. Self::Directory {
  246. accessor,
  247. owner,
  248. flags,
  249. ..
  250. } => (accessor, owner, flags),
  251. };
  252. let accessor = Arc::try_unwrap(accessor).map_err(|_| {
  253. bterr!("LOGIC ERROR: accessor was still in use even though convert_to_dir owns it")
  254. })?;
  255. let accessor = accessor
  256. .into_inner()
  257. .ok_or_else(|| bterr!("LOGIC ERROR: accessor was not returned to mutex"))?;
  258. let mut accessor = Accessor::combine(accessor, block);
  259. let dir = accessor.read_dir()?;
  260. let (accessor, ..) = accessor.split();
  261. Ok(HandleValue::Directory {
  262. dir,
  263. accessor: Arc::new(Mutex::new(Some(accessor))),
  264. owner,
  265. flags,
  266. })
  267. }
  268. fn directory(&self) -> io::Result<&Directory> {
  269. match self {
  270. Self::Directory { dir, .. } => Ok(dir),
  271. _ => Err(io::Error::new(
  272. io::ErrorKind::Other,
  273. "handle is not for a directory",
  274. )),
  275. }
  276. }
  277. async fn lock(&self, from: &BlockPath) -> Result<(Flags, OwnedMutexGuard<EmptyAccessor>)> {
  278. let (mutex, owner, flags) = self.parts();
  279. owner.assert_eq(from)?;
  280. Ok((flags, mutex.clone().lock_owned().await))
  281. }
  282. async fn guard<'a, B: Size>(
  283. &'a self,
  284. from: &BlockPath,
  285. block: B,
  286. ) -> Result<HandleGuard<B, MutexGuard<'a, EmptyAccessor>>> {
  287. let (mutex, owner, flags) = self.parts();
  288. owner.assert_eq(from)?;
  289. let guard = mutex.lock().await;
  290. Ok(HandleGuard::new(flags, guard, block))
  291. }
  292. fn set_flags(&mut self, new_flags: Flags) {
  293. match self {
  294. Self::File { flags, .. } => *flags = new_flags,
  295. Self::Directory { flags, .. } => *flags = new_flags,
  296. }
  297. }
  298. }
  299. struct BlockGuard<B> {
  300. inner: B,
  301. }
  302. impl<B> BlockGuard<B> {
  303. fn new(inner: B) -> Self {
  304. Self { inner }
  305. }
  306. }
  307. impl<C, B: Deref<Target = InodeTableValue<C>>> Deref for BlockGuard<B> {
  308. type Target = FileBlock<C>;
  309. fn deref(&self) -> &Self::Target {
  310. self.inner.block.get_ref()
  311. }
  312. }
  313. impl<C, B: DerefMut<Target = InodeTableValue<C>>> DerefMut for BlockGuard<B> {
  314. fn deref_mut(&mut self) -> &mut Self::Target {
  315. self.inner.block.get_mut()
  316. }
  317. }
  318. impl<C, B: Deref<Target = InodeTableValue<C>>> Size for BlockGuard<B> {
  319. fn size(&self) -> io::Result<Option<u64>> {
  320. self.inner.block.size()
  321. }
  322. }
  323. impl<C, B: Deref<Target = InodeTableValue<C>>> ReadAt for BlockGuard<B> {
  324. fn read_at(&self, pos: u64, buf: &mut [u8]) -> io::Result<usize> {
  325. self.inner.block.get_ref().read_at(pos, buf)
  326. }
  327. }
  328. impl<C: 'static, B: Deref<Target = InodeTableValue<C>>> AsRef<BlockMeta> for BlockGuard<B> {
  329. fn as_ref(&self) -> &BlockMeta {
  330. self.inner.block.as_ref()
  331. }
  332. }
  333. pub struct InodeTableValue<C> {
  334. block: Accessor<FileBlock<C>>,
  335. handle_values: HashMap<Handle, HandleValue>,
  336. next_handle: Handle,
  337. lookup_counts: HashMap<Arc<BlockPath>, u64>,
  338. delete: bool,
  339. }
  340. impl<C: Signer + Principaled + Decrypter> InodeTableValue<C> {
  341. fn new(block: Accessor<FileBlock<C>>, opener: Arc<BlockPath>) -> InodeTableValue<C> {
  342. let mut lookup_counts = HashMap::with_capacity(1);
  343. lookup_counts.insert(opener, 1);
  344. Self {
  345. block,
  346. handle_values: HashMap::new(),
  347. next_handle: 1,
  348. lookup_counts,
  349. delete: false,
  350. }
  351. }
  352. fn invalid_handle_err(handle: Handle) -> io::Error {
  353. io::Error::new(io::ErrorKind::Other, format!("invalid handle {handle}"))
  354. }
  355. fn value(&self, handle: Handle) -> io::Result<&HandleValue> {
  356. self.handle_values
  357. .get(&handle)
  358. .ok_or_else(|| Self::invalid_handle_err(handle))
  359. }
  360. fn block(&self) -> &FileBlock<C> {
  361. self.block.get_ref()
  362. }
  363. fn block_mut(&mut self) -> &mut FileBlock<C> {
  364. self.block.get_mut()
  365. }
  366. fn convert_to_dir(&mut self, handle: Handle) -> io::Result<()> {
  367. let value = self
  368. .handle_values
  369. .remove(&handle)
  370. .ok_or_else(|| Self::invalid_handle_err(handle))?;
  371. let block = self.block_mut();
  372. let value = value.convert_to_dir(block)?;
  373. self.handle_values.insert(handle, value);
  374. Ok(())
  375. }
  376. async fn handle_guard<'a>(
  377. &'a self,
  378. from: &BlockPath,
  379. handle: Handle,
  380. ) -> Result<HandleGuard<&FileBlock<C>, MutexGuard<'a, EmptyAccessor>>> {
  381. let value = self.value(handle)?;
  382. let block = self.block();
  383. value.guard(from, block).await
  384. }
  385. async fn handle_guard_owned(
  386. guard: OwnedRwLockReadGuard<Self>,
  387. from: &BlockPath,
  388. handle: Handle,
  389. ) -> Result<
  390. HandleGuard<BlockGuard<OwnedRwLockReadGuard<Self>>, OwnedMutexGuard<EmptyAccessor>>,
  391. > {
  392. let value = guard.value(handle)?;
  393. let (flags, mutex_guard) = value.lock(from).await?;
  394. let guard = BlockGuard::new(guard);
  395. Ok(HandleGuard::new(flags, mutex_guard, guard))
  396. }
  397. async fn handle_guard_mut<'a>(
  398. &'a mut self,
  399. from: &BlockPath,
  400. handle: Handle,
  401. ) -> Result<HandleGuard<&mut FileBlock<C>, MutexGuard<'a, EmptyAccessor>>> {
  402. let value = self
  403. .handle_values
  404. .get(&handle)
  405. .ok_or_else(|| Self::invalid_handle_err(handle))?;
  406. if !value.flags().writeable() {
  407. return Err(Error::ReadOnlyHandle(handle).into());
  408. }
  409. let inner = self.block.get_mut();
  410. value.guard(from, inner).await
  411. }
  412. fn new_handle(&mut self, owner: Arc<BlockPath>, flags: Flags) -> Result<Handle> {
  413. if self.handle_values.len() as u64 >= u64::MAX {
  414. return Err(bterr!("no handles are available"));
  415. }
  416. let mut handle_value = HandleValue::new(Accessor::new(self.block())?, owner, flags);
  417. loop {
  418. let handle = self.next_handle;
  419. self.next_handle = self.next_handle.wrapping_add(1);
  420. match self.handle_values.insert(handle, handle_value) {
  421. Some(prev) => {
  422. // We've wrapped around and this handle is already taken. Put the previous
  423. // value back and try again.
  424. handle_value = self.handle_values.insert(handle, prev).unwrap();
  425. }
  426. // We generated an unused handle. Return it.
  427. None => return Ok(handle),
  428. }
  429. }
  430. }
  431. fn set_flags(&mut self, handle: Handle, flags: Flags) -> Result<()> {
  432. let handle_value = self
  433. .handle_values
  434. .get_mut(&handle)
  435. .ok_or_else(|| Self::invalid_handle_err(handle))?;
  436. handle_value.set_flags(flags);
  437. Ok(())
  438. }
  439. fn forget_handle(&mut self, handle: Handle) {
  440. self.handle_values.remove(&handle);
  441. }
  442. /// Increments the lookup count from the given path by 1.
  443. fn incr_lookup_count(&mut self, from: &Arc<BlockPath>) {
  444. match self.lookup_counts.entry(from.clone()) {
  445. hash_map::Entry::Occupied(mut entry) => {
  446. // I don't want this to silently overflow.
  447. let new_count = entry.get().checked_add(1).unwrap();
  448. *entry.get_mut() = new_count;
  449. }
  450. hash_map::Entry::Vacant(entry) => {
  451. entry.insert(1);
  452. }
  453. }
  454. }
  455. /// Decrements the lookup count from the given path by the given amount.
  456. fn decr_lookup_count(&mut self, from: Arc<BlockPath>, decr: u64) {
  457. match self.lookup_counts.entry(from) {
  458. hash_map::Entry::Occupied(mut entry) => {
  459. let new_count = entry.get().saturating_sub(decr);
  460. if new_count > 0 {
  461. *entry.get_mut() = new_count;
  462. } else {
  463. entry.remove();
  464. }
  465. }
  466. hash_map::Entry::Vacant(..) => (),
  467. }
  468. }
  469. fn total_lookup_count(&self) -> u64 {
  470. self.lookup_counts.values().sum()
  471. }
  472. }
  473. type InodeTable<C> = HashMap<Inode, Arc<RwLock<InodeTableValue<C>>>>;
  474. type OwnedTableLock<C> = OwnedRwLockReadGuard<InodeTable<C>>;
  475. type TableLock<'a, C> = RwLockReadGuard<'a, InodeTable<C>>;
  476. struct TableGuard<G> {
  477. table_guard: G,
  478. }
  479. impl<C> TableGuard<OwnedRwLockReadGuard<C>> {
  480. async fn new_owned(table: Arc<RwLock<InodeTable<C>>>) -> TableGuard<OwnedTableLock<C>> {
  481. let table_guard = table.read_owned().await;
  482. TableGuard { table_guard }
  483. }
  484. }
  485. impl<'a, C> TableGuard<TableLock<'a, C>> {
  486. async fn new(table: &'a RwLock<InodeTable<C>>) -> TableGuard<TableLock<'a, C>> {
  487. let table_guard = table.read().await;
  488. TableGuard { table_guard }
  489. }
  490. }
  491. impl<C, G: Deref<Target = InodeTable<C>>> TableGuard<G> {
  492. fn get_value(&self, inode: Inode) -> Result<&Arc<RwLock<InodeTableValue<C>>>> {
  493. self.table_guard
  494. .get(&inode)
  495. .ok_or_else(|| bterr!(Error::NotOpen(inode)))
  496. }
  497. async fn read<'a>(&'a self, inode: Inode) -> Result<RwLockReadGuard<'a, InodeTableValue<C>>>
  498. where
  499. C: 'a,
  500. {
  501. let value = self.get_value(inode)?;
  502. Ok(value.read().await)
  503. }
  504. async fn write<'a>(
  505. &'a self,
  506. inode: Inode,
  507. ) -> Result<RwLockWriteGuard<'a, InodeTableValue<C>>>
  508. where
  509. C: 'a,
  510. {
  511. let value = self.get_value(inode)?;
  512. Ok(value.write().await)
  513. }
  514. }
  515. /// Structure for metadata about a blocktree.
  516. #[derive(Debug, Serialize, Deserialize, ZeroizeOnDrop)]
  517. struct Superblock {
  518. /// The generation number of the cluster this part of the blocktree is stored on.
  519. generation: u64,
  520. /// The next free inode available to the cluster.
  521. #[zeroize(skip)]
  522. next_inode: AtomicU64,
  523. /// The hash algorithm to use when computing inode paths.
  524. #[zeroize(skip)]
  525. inode_hash: HashKind,
  526. /// The key to use when hashing inodes to file paths.
  527. inode_key: Vec<u8>,
  528. }
  529. /// Structure for managing the part of a blocktree which is stored in the local filesystem.
  530. pub struct LocalFs<C, A> {
  531. /// The path to the directory in the local filesystem where this blocktree is located.
  532. path: PathBuf,
  533. /// A map from inode numbers to their reference counts.
  534. inodes: Arc<RwLock<InodeTable<C>>>,
  535. /// An in-memory copy of the superblock.
  536. sb: Superblock,
  537. /// The credentials this blocktree instance will use for all cryptographic operations.
  538. creds: C,
  539. authorizer: A,
  540. root_principal: Principal,
  541. }
  542. impl<C, A> LocalFs<C, A> {
  543. /// The maximum number of directory entries that can be returned in any given call to
  544. /// `read_dir`.
  545. const READ_DIR_LIMIT: usize = 1024;
  546. }
  547. impl<C: Creds + 'static, A: Authorizer> LocalFs<C, A> {
  548. /// Creates a new empty blocktree at the given path.
  549. pub async fn new_empty(
  550. btdir: PathBuf,
  551. generation: u64,
  552. creds: C,
  553. authorizer: A,
  554. ) -> Result<LocalFs<C, A>> {
  555. let writecap = creds.writecap().ok_or(BlockError::MissingWritecap)?;
  556. let mut root_block_path = writecap.root_block_path();
  557. let root_principal = writecap.root_principal();
  558. // Initialize the superblock.
  559. let mut sb_block = Self::open_superblock(
  560. &btdir,
  561. creds.clone(),
  562. root_block_path.clone(),
  563. &root_principal,
  564. true,
  565. )?;
  566. let sb = Superblock {
  567. generation,
  568. next_inode: AtomicU64::new(SpecInodes::FirstFree.into()),
  569. inode_hash: HashKind::default(),
  570. inode_key: rand_vec(HashKind::default().len())?,
  571. };
  572. write_to(&sb, &mut sb_block)?;
  573. sb_block.mut_meta_body().access_secrets(|secrets| {
  574. secrets.block_id.generation = generation;
  575. secrets.block_id.inode = SpecInodes::Sb.into();
  576. secrets.mode = FileType::Reg.value() | 0o666;
  577. secrets.uid = 0;
  578. secrets.gid = 0;
  579. secrets.nlink = 1;
  580. Ok(())
  581. })?;
  582. sb_block.flush()?;
  583. // Initialize the root directory.
  584. let mut root_block = Self::open_block(
  585. &btdir,
  586. SpecInodes::RootDir.into(),
  587. creds.clone(),
  588. root_block_path.clone(),
  589. None,
  590. sb.inode_hash,
  591. &sb.inode_key,
  592. )?;
  593. write_to(&Directory::new(), &mut root_block)?;
  594. root_block.mut_meta_body().access_secrets(|secrets| {
  595. secrets.block_id.generation = generation;
  596. secrets.block_id.inode = SpecInodes::RootDir.into();
  597. secrets.mode = FileType::Dir.value() | 0o777;
  598. secrets.uid = 0;
  599. secrets.gid = 0;
  600. secrets.nlink = 1;
  601. Ok(())
  602. })?;
  603. root_block.flush()?;
  604. let fs = Self::new(
  605. btdir,
  606. sb,
  607. sb_block,
  608. root_block,
  609. creds,
  610. authorizer,
  611. root_principal,
  612. )?;
  613. let writecap = fs.creds.writecap().ok_or(BlockError::MissingWritecap)?;
  614. if fs.creds.principal() != fs.root_principal {
  615. let proc_rec = IssuedProcRec {
  616. addr: IpAddr::V6(Ipv6Addr::LOCALHOST),
  617. pub_creds: fs.creds.concrete_pub(),
  618. writecap: writecap.to_owned(),
  619. authz_attrs: AuthzAttrs {
  620. uid: 0,
  621. gid: 0,
  622. supp_gids: Vec::new(),
  623. },
  624. };
  625. root_block_path.push_component(fs.root_principal.to_string());
  626. fs.grant_access_to(
  627. &Arc::new(root_block_path),
  628. SpecInodes::RootDir.into(),
  629. proc_rec,
  630. )
  631. .await?;
  632. }
  633. Ok(fs)
  634. }
  635. /// Opens an existing blocktree stored at the given path.
  636. pub fn new_existing(btdir: PathBuf, creds: C, authorizer: A) -> Result<LocalFs<C, A>> {
  637. let writecap = creds.writecap().ok_or(BlockError::MissingWritecap)?;
  638. let root_block_path = writecap.root_block_path();
  639. let root_principal = writecap.root_principal();
  640. let mut sb_block = Self::open_superblock(
  641. &btdir,
  642. creds.clone(),
  643. root_block_path.clone(),
  644. &root_principal,
  645. false,
  646. )?;
  647. let sb: Superblock = read_from(&mut sb_block)?;
  648. let root_block = Self::open_block(
  649. &btdir,
  650. SpecInodes::RootDir.into(),
  651. creds.clone(),
  652. root_block_path,
  653. None,
  654. sb.inode_hash,
  655. &sb.inode_key,
  656. )?;
  657. Self::new(
  658. btdir,
  659. sb,
  660. sb_block,
  661. root_block,
  662. creds,
  663. authorizer,
  664. root_principal,
  665. )
  666. }
  667. fn new(
  668. btdir: PathBuf,
  669. sb: Superblock,
  670. sb_block: Accessor<FileBlock<C>>,
  671. root_block: Accessor<FileBlock<C>>,
  672. creds: C,
  673. authorizer: A,
  674. root_principal: Principal,
  675. ) -> Result<LocalFs<C, A>> {
  676. let mut inodes = HashMap::with_capacity(1);
  677. let empty_path = Arc::new(BlockPath::default());
  678. inodes.insert(
  679. SpecInodes::Sb.into(),
  680. Arc::new(RwLock::new(InodeTableValue::new(
  681. sb_block,
  682. empty_path.clone(),
  683. ))),
  684. );
  685. inodes.insert(
  686. SpecInodes::RootDir.into(),
  687. Arc::new(RwLock::new(InodeTableValue::new(root_block, empty_path))),
  688. );
  689. Ok(LocalFs {
  690. path: btdir,
  691. inodes: Arc::new(RwLock::new(inodes)),
  692. sb,
  693. creds,
  694. authorizer,
  695. root_principal,
  696. })
  697. }
  698. fn make_path<P: AsRef<Path>>(parent: P, file_name: &str) -> PathBuf {
  699. let mut path =
  700. PathBuf::with_capacity(parent.as_ref().as_os_str().len() + 1 + file_name.len() + 1);
  701. path.push(parent);
  702. path.push(&file_name[..2]);
  703. path.push(&file_name[2..]);
  704. path
  705. }
  706. fn hex_encode(src: &[u8]) -> Result<String> {
  707. use std::fmt::Write;
  708. let mut string = String::with_capacity(2 * src.len());
  709. for byte in src.iter() {
  710. write!(string, "{byte:02x}")?;
  711. }
  712. Ok(string)
  713. }
  714. fn ensure_parent_created(path: &Path) -> Result<()> {
  715. let dir = path.ancestors().nth(1).unwrap();
  716. if let Err(err) = std::fs::create_dir(dir) {
  717. match err.kind() {
  718. io::ErrorKind::AlreadyExists => Ok(()),
  719. _ => Err(err.into()),
  720. }
  721. } else {
  722. Ok(())
  723. }
  724. }
  725. fn open_superblock<P: AsRef<Path>>(
  726. btdir: P,
  727. creds: C,
  728. block_path: BlockPath,
  729. root_principal: &Principal,
  730. create_new: bool,
  731. ) -> Result<Accessor<FileBlock<C>>> {
  732. const HASH: HashKind = HashKind::Sha2_256;
  733. let mut buf = [0u8; HASH.len()];
  734. HASH.digest(
  735. &mut buf,
  736. [
  737. SpecInodes::Sb.value().to_le_bytes().as_slice(),
  738. root_principal.as_slice(),
  739. ]
  740. .into_iter(),
  741. )?;
  742. let hex_str = Self::hex_encode(&buf)?;
  743. let path = Self::make_path(btdir, &hex_str);
  744. Self::ensure_parent_created(&path)?;
  745. let file = std::fs::OpenOptions::new()
  746. .read(true)
  747. .write(true)
  748. .create_new(create_new)
  749. .open(path)?;
  750. let block = BlockOpenOptions::new()
  751. .with_creds(creds)
  752. .with_encrypt(true)
  753. .with_inner(file)
  754. .with_block_path(block_path)
  755. .open()?;
  756. Ok(block)
  757. }
  758. /// Returns the path to the file storing the given inode's data.
  759. fn block_path<P: AsRef<Path>>(
  760. parent: P,
  761. inode: Inode,
  762. inode_hash: HashKind,
  763. inode_key: &[u8],
  764. ) -> Result<PathBuf> {
  765. let mut buf = vec![0u8; inode_hash.len()];
  766. inode_hash.digest(
  767. &mut buf,
  768. [inode.to_le_bytes().as_slice(), inode_key].into_iter(),
  769. )?;
  770. let hex_str = Self::hex_encode(&buf)?;
  771. Ok(Self::make_path(parent, &hex_str))
  772. }
  773. fn open_block<P: AsRef<Path>>(
  774. btdir: P,
  775. inode: Inode,
  776. creds: C,
  777. block_path: BlockPath,
  778. parent_key: Option<SymKey>,
  779. inode_hash: HashKind,
  780. inode_key: &[u8],
  781. ) -> Result<Accessor<FileBlock<C>>> {
  782. let path = Self::block_path(&btdir, inode, inode_hash, inode_key)?;
  783. Self::ensure_parent_created(&path)?;
  784. let file = std::fs::OpenOptions::new()
  785. .read(true)
  786. .write(true)
  787. .create(true)
  788. .open(path)?;
  789. Self::open_block_file(file, creds, block_path, parent_key)
  790. }
  791. fn open_block_file(
  792. file: File,
  793. creds: C,
  794. block_path: BlockPath,
  795. parent_key: Option<SymKey>,
  796. ) -> Result<Accessor<FileBlock<C>>> {
  797. let block = BlockOpenOptions::new()
  798. .with_creds(creds)
  799. .with_encrypt(true)
  800. .with_inner(file)
  801. .with_parent_key(parent_key)
  802. .with_block_path(block_path)
  803. .open()?;
  804. Ok(block)
  805. }
  806. async fn table_guard(&self) -> TableGuard<TableLock<'_, C>> {
  807. TableGuard::new(&self.inodes).await
  808. }
  809. async fn open_value(
  810. &self,
  811. from: Arc<BlockPath>,
  812. inode: Inode,
  813. block_path: BlockPath,
  814. parent_key: Option<SymKey>,
  815. ) -> Result<()> {
  816. let block = Self::open_block(
  817. &self.path,
  818. inode,
  819. self.creds.clone(),
  820. block_path,
  821. parent_key,
  822. self.sb.inode_hash,
  823. &self.sb.inode_key,
  824. )?;
  825. let value = Arc::new(RwLock::new(InodeTableValue::new(block, from)));
  826. let mut inodes = self.inodes.write().await;
  827. if inodes.insert(inode, value).is_some() {
  828. error!(
  829. "LOGIC ERROR: open_value was called with inode {inode}, which is already open"
  830. );
  831. }
  832. Ok(())
  833. }
  834. /// Ensures that the given inode is open. If the inode is already open, then this method
  835. /// does nothing and returns the table guard which was used to check the status of the
  836. /// inode.
  837. /// ## Warning
  838. /// Because this method creates new table guards, no table guard must be alive when it's
  839. /// called. Otherwise a deadlock will occur.
  840. async fn ensure_open<'a>(
  841. &'a self,
  842. from: &Arc<BlockPath>,
  843. inode: Inode,
  844. block_path: BlockPath,
  845. parent_key: Option<SymKey>,
  846. ) -> Result<TableGuard<OwnedTableLock<C>>> {
  847. {
  848. let table_guard = self.inodes.clone().read_owned().await;
  849. if table_guard.contains_key(&inode) {
  850. return Ok(TableGuard { table_guard });
  851. }
  852. }
  853. self.open_value(from.clone(), inode, block_path, parent_key)
  854. .await?;
  855. Ok(TableGuard::new_owned(self.inodes.clone()).await)
  856. }
  857. fn delete_block_file(&self, inode: Inode) -> Result<()> {
  858. let mut path =
  859. Self::block_path(&self.path, inode, self.sb.inode_hash, &self.sb.inode_key)?;
  860. std::fs::remove_file(&path)?;
  861. path.pop();
  862. let mut contents = std::fs::read_dir(&path)?;
  863. if contents.next().is_none() {
  864. std::fs::remove_dir(&path)?;
  865. }
  866. Ok(())
  867. }
  868. async fn inode_forget<'a>(
  869. &self,
  870. from: Arc<BlockPath>,
  871. inode: Inode,
  872. count: u64,
  873. ) -> io::Result<()> {
  874. let mut inodes = self.inodes.write().await;
  875. let lookup_count = {
  876. let inode_lock = match inodes.get_mut(&inode) {
  877. Some(inode_lock) => inode_lock,
  878. None => {
  879. warn!("an attempt was made to forget non-existent inode {inode}");
  880. return Ok(());
  881. }
  882. };
  883. let mut value = inode_lock.write().await;
  884. value.decr_lookup_count(from, count);
  885. value.total_lookup_count()
  886. };
  887. if 0 == lookup_count {
  888. let entry = Arc::try_unwrap(inodes.remove(&inode).unwrap())
  889. .map_err(|_| bterr!("LOGIC ERROR: entry for inode {inode} was still in use while it was being forgotten"))?;
  890. let delete = entry.into_inner().delete;
  891. if delete {
  892. self.delete_block_file(inode)?;
  893. }
  894. }
  895. Ok(())
  896. }
  897. /// Returns the next available inode and updates the superblock in one atomic operation.
  898. /// TODO: Obviously this strategy won't work when there are multiple servers in this
  899. /// generation.
  900. async fn next_inode(&self) -> Result<Inode> {
  901. let table_guard = self.table_guard().await;
  902. let mut value_guard = table_guard.write(SpecInodes::Sb.into()).await?;
  903. let mut block = &mut value_guard.block;
  904. // We don't need strict ordering because the lock on the inode table value is already
  905. // serializing access.
  906. let inode = self.sb.next_inode.fetch_add(1, Ordering::Relaxed);
  907. block.rewind()?;
  908. write_to(&self.sb, &mut block)?;
  909. block.flush()?;
  910. Ok(inode)
  911. }
  912. fn attr_timeout(&self) -> Duration {
  913. Duration::from_secs(5)
  914. }
  915. fn entry_timeout(&self) -> Duration {
  916. Duration::from_secs(5)
  917. }
  918. fn unsupported_flag_err(flag: &str) -> btlib::Error {
  919. bterr!("unsupported flag: {flag}")
  920. }
  921. fn bt_entry(&self, attr: BlockMetaSecrets) -> crate::msg::Entry {
  922. crate::msg::Entry {
  923. attr,
  924. attr_timeout: self.attr_timeout(),
  925. entry_timeout: self.entry_timeout(),
  926. }
  927. }
  928. /// Grants the given credentials access to the directory this instance is responsible for.
  929. ///
  930. /// ## Warning
  931. /// This method calls `self.authz_attrs`, so the same consideration for avoiding deadlock
  932. /// apply to this method as well. See the documentation of `self.authz_attrs` for details.
  933. async fn grant_access_to(
  934. &self,
  935. from: &Arc<BlockPath>,
  936. inode: Inode,
  937. proc_rec: IssuedProcRec,
  938. ) -> Result<()> {
  939. let authz_attrs = self.authz_attrs(from).await?;
  940. let principal = proc_rec.pub_creds.principal();
  941. let (next_inode, parent_key) = {
  942. let table_guard = self.table_guard().await;
  943. let next_inode = if inode == SpecInodes::RootDir.value() {
  944. // If the inode is for the root directory we need to add a readcap for the
  945. // superblock.
  946. let mut value_guard = table_guard.write(SpecInodes::Sb.into()).await?;
  947. let mut block = &mut value_guard.block;
  948. let next_inode = self.sb.next_inode.fetch_add(1, Ordering::Relaxed);
  949. block.rewind()?;
  950. write_to(&self.sb, &mut block)?;
  951. block.mut_meta_body().add_readcap_for(&proc_rec.pub_creds)?;
  952. block.flush()?;
  953. Ok(next_inode)
  954. } else {
  955. self.next_inode().await
  956. }?;
  957. let parent_key = {
  958. let mut value_guard = table_guard.write(inode).await?;
  959. let block = &mut value_guard.block;
  960. self.authorizer.can_write(&AuthzContext::new(
  961. from,
  962. &authz_attrs,
  963. block.meta(),
  964. ))?;
  965. block.mut_meta_body().add_readcap_for(&proc_rec.pub_creds)?;
  966. let mut dir = block.read_dir()?;
  967. let proc_rec_name = principal.to_string();
  968. dir.add_file(proc_rec_name, next_inode)?;
  969. // Note that write_dir calls flush, which also ensures metadata is written to
  970. // disk.
  971. block.write_dir(&dir)?;
  972. block.meta_body().block_key()?.clone()
  973. };
  974. (next_inode, parent_key)
  975. };
  976. let self_writecap = self.creds.writecap().ok_or(BlockError::MissingWritecap)?;
  977. let self_bind_path = Arc::new(self_writecap.bind_path());
  978. let bind_path = proc_rec.writecap.bind_path();
  979. self.open_value(
  980. self_bind_path.clone(),
  981. next_inode,
  982. bind_path,
  983. Some(parent_key),
  984. )
  985. .await?;
  986. {
  987. let table_guard = self.table_guard().await;
  988. let mut value_guard = table_guard.write(next_inode).await?;
  989. let block = &mut value_guard.block;
  990. block.write_proc_rec(&ProcRec::Valid(proc_rec))?;
  991. };
  992. // We must ensure the reference count for the inode is decremented, otherwise the table
  993. // entry will never be freed.
  994. self.inode_forget(self_bind_path, next_inode, 1).await?;
  995. Ok(())
  996. }
  997. async fn lookup_inode_in<'a>(
  998. table_guard: &'a TableGuard<TableLock<'a, C>>,
  999. parent: Inode,
  1000. name: &str,
  1001. ) -> Result<Inode> {
  1002. let mut value_guard = table_guard.write(parent).await?;
  1003. let dir = value_guard.block.read_dir()?;
  1004. dir.entry(name)
  1005. .ok_or_else(|| io::Error::from_raw_os_error(libc::ENOENT).into())
  1006. .map(|e| e.inode())
  1007. }
  1008. /// Returns a pair of inodes, where the first inode is the inode referred to by the given
  1009. /// path, and the second is the parent inode.
  1010. async fn lookup_inode<'a, 'b, I: Iterator<Item = &'a str>>(
  1011. table_guard: &'b TableGuard<TableLock<'b, C>>,
  1012. components: I,
  1013. ) -> Result<(Inode, Option<Inode>)> {
  1014. const ROOT: Inode = SpecInodes::RootDir as Inode;
  1015. let mut parent = None;
  1016. let mut inode = ROOT;
  1017. for component in components {
  1018. parent = Some(inode);
  1019. inode = Self::lookup_inode_in(table_guard, inode, component).await?;
  1020. }
  1021. Ok((inode, parent))
  1022. }
  1023. /// Retrieves the authorization attributes for the principal identified by the given path.
  1024. /// If the principal is not associated with a valid process record, then an [Err] is
  1025. /// returned.
  1026. /// ## Warning
  1027. /// If this method is called while a lock for any component on the given path is held, then
  1028. /// a deadlock may occur. It's safest to call this method when _no_ locks are held.
  1029. async fn authz_attrs(&self, from: &Arc<BlockPath>) -> Result<AuthzAttrs> {
  1030. let writecap = self.creds.writecap().ok_or(BlockError::MissingWritecap)?;
  1031. let root_principal = writecap.root_principal();
  1032. let from_principal = from.components().last().map_or_else(
  1033. || Err(bterr!("path from which message was received was empty")),
  1034. Principal::try_from,
  1035. )?;
  1036. if root_principal == from_principal {
  1037. // Now I am become root, the destroyer of files.
  1038. return Ok(AuthzAttrs {
  1039. uid: 0,
  1040. gid: 0,
  1041. supp_gids: Vec::new(),
  1042. });
  1043. }
  1044. let local_root = writecap.path();
  1045. let relative = from.relative_to(local_root)?;
  1046. let (inode, parent_key) = {
  1047. let table_guard = self.table_guard().await;
  1048. let (inode, parent) =
  1049. Self::lookup_inode(&table_guard, relative.components()).await?;
  1050. let parent_key = if let Some(parent) = parent {
  1051. let value_guard = table_guard.read(parent).await?;
  1052. Some(value_guard.block.meta_body().block_key()?.clone())
  1053. } else {
  1054. None
  1055. };
  1056. (inode, parent_key)
  1057. };
  1058. let proc_rec = {
  1059. let table_guard = self
  1060. .ensure_open(from, inode, from.as_ref().to_owned(), parent_key)
  1061. .await?;
  1062. let mut value_guard = table_guard.write(inode).await?;
  1063. value_guard.block.read_proc_rec()?
  1064. };
  1065. let proc_rec = proc_rec.validate()?;
  1066. Ok(proc_rec.authz_attrs)
  1067. }
  1068. }
  1069. unsafe impl<C: Sync, A: Sync> Sync for LocalFs<C, A> {}
  1070. /// An owned guard which allows read access to file data.
  1071. pub struct BufGuard<C> {
  1072. offset: u64,
  1073. size: u64,
  1074. // Note that handle must come before _table to ensure the guards are dropped in the correct
  1075. // order.
  1076. handle: HandleGuard<
  1077. BlockGuard<OwnedRwLockReadGuard<InodeTableValue<C>>>,
  1078. OwnedMutexGuard<EmptyAccessor>,
  1079. >,
  1080. _table: OwnedTableLock<C>,
  1081. }
  1082. impl<C: 'static + Principaled + Signer + Decrypter> BufGuard<C> {
  1083. async fn new(
  1084. table: Arc<RwLock<InodeTable<C>>>,
  1085. from: &BlockPath,
  1086. inode: Inode,
  1087. handle: Handle,
  1088. offset: u64,
  1089. size: u64,
  1090. ) -> Result<BufGuard<C>> {
  1091. let table = table.read_owned().await;
  1092. let entry = table.get(&inode).ok_or(Error::NotOpen(inode))?;
  1093. let inode_guard = {
  1094. let inode_guard = entry.clone().read_owned().await;
  1095. let mut handle_guard = inode_guard.handle_guard(from, handle).await?;
  1096. handle_guard.flags.assert_readable()?;
  1097. let pos = handle_guard.pos() as u64;
  1098. if offset != pos {
  1099. if let Err(err) = handle_guard.try_seek(SeekFrom::Start(offset)) {
  1100. // An error with `ErrorKind::Unsupported` means that the `SectoredBuf`
  1101. // has unflushed data and it needs exclusive access to the block to
  1102. // perform this seek because this data needs to be written.
  1103. if let io::ErrorKind::Unsupported = err.kind() {
  1104. None
  1105. } else {
  1106. return Err(err.into());
  1107. }
  1108. } else {
  1109. drop(handle_guard);
  1110. Some(inode_guard)
  1111. }
  1112. } else {
  1113. drop(handle_guard);
  1114. Some(inode_guard)
  1115. }
  1116. };
  1117. let inode_guard = match inode_guard {
  1118. Some(inode_guard) => inode_guard,
  1119. None => {
  1120. {
  1121. let mut inode_guard = entry.write().await;
  1122. let mut handle_guard = inode_guard.handle_guard_mut(from, handle).await?;
  1123. handle_guard.seek(SeekFrom::Start(offset))?;
  1124. }
  1125. entry.clone().read_owned().await
  1126. }
  1127. };
  1128. let handle = InodeTableValue::handle_guard_owned(inode_guard, from, handle).await?;
  1129. Ok(BufGuard {
  1130. handle,
  1131. _table: table,
  1132. offset,
  1133. size,
  1134. })
  1135. }
  1136. }
  1137. impl<C: 'static + Principaled + Decrypter + Signer> Deref for BufGuard<C> {
  1138. type Target = [u8];
  1139. fn deref(&self) -> &Self::Target {
  1140. self.handle.get_buf(self.offset, self.size).unwrap()
  1141. }
  1142. }
  1143. impl<C: 'static + Creds + Clone + Send + Sync, A: 'static + Authorizer + Send + Sync> FsProvider
  1144. for LocalFs<C, A>
  1145. {
  1146. type LookupFut<'c> = impl 'c + Send + Future<Output = Result<LookupReply>>;
  1147. fn lookup<'c>(&'c self, from: &'c Arc<BlockPath>, msg: Lookup<'c>) -> Self::LookupFut<'c> {
  1148. async move {
  1149. let Lookup { parent, name, .. } = msg;
  1150. debug!("lookup: parent {parent}, {:?}", name);
  1151. let authz_attrs = self.authz_attrs(from).await?;
  1152. let (dir, block_path, parent_key) = {
  1153. let table_guard = self.table_guard().await;
  1154. let mut value_guard = table_guard.write(parent).await?;
  1155. let parent_block = &mut value_guard.block;
  1156. self.authorizer.can_exec(&AuthzContext::new(
  1157. from,
  1158. &authz_attrs,
  1159. parent_block.meta(),
  1160. ))?;
  1161. let dir = parent_block.read_dir()?;
  1162. let meta_body = parent_block.meta_body();
  1163. let block_path = meta_body.path().to_owned();
  1164. let parent_key = meta_body.block_key()?.clone();
  1165. (dir, block_path, parent_key)
  1166. };
  1167. let entry = dir
  1168. .entry(name)
  1169. .ok_or_else(|| io::Error::from_raw_os_error(libc::ENOENT))?;
  1170. let inode = entry.inode();
  1171. let stat = {
  1172. let table_guard = self
  1173. .ensure_open(from, inode, block_path, Some(parent_key))
  1174. .await?;
  1175. let mut value_guard = table_guard.write(inode).await?;
  1176. let stat = value_guard.block.meta_body().secrets()?.to_owned();
  1177. value_guard.incr_lookup_count(from);
  1178. stat
  1179. };
  1180. let entry = self.bt_entry(stat);
  1181. let reply = LookupReply {
  1182. inode,
  1183. generation: self.sb.generation,
  1184. entry,
  1185. };
  1186. Ok(reply)
  1187. }
  1188. }
  1189. type CreateFut<'c> = impl 'c + Send + Future<Output = Result<CreateReply>>;
  1190. fn create<'c>(&'c self, from: &'c Arc<BlockPath>, msg: Create<'c>) -> Self::CreateFut<'c> {
  1191. async move {
  1192. let Create {
  1193. parent,
  1194. name,
  1195. flags,
  1196. mode,
  1197. umask,
  1198. } = msg;
  1199. debug!("create: parent {parent}, name {:?}", name);
  1200. let authz_attrs = self.authz_attrs(from).await?;
  1201. let name = msg.name.to_owned();
  1202. // Add a directory entry to the parent for the new inode.
  1203. let (inode, mut block_path, parent_key) = {
  1204. let table_guard = self.table_guard().await;
  1205. let mut value_guard = table_guard.write(parent).await?;
  1206. let block = &mut value_guard.block;
  1207. self.authorizer.can_write(&AuthzContext::new(
  1208. from,
  1209. &authz_attrs,
  1210. block.meta(),
  1211. ))?;
  1212. let mut dir = block.read_dir()?;
  1213. if dir.contains_entry(&name) {
  1214. return Err(io::Error::from_raw_os_error(libc::EEXIST).into());
  1215. }
  1216. // Reserve a free inode.
  1217. let inode = self.next_inode().await?;
  1218. dir.add_file(name.clone(), inode)?;
  1219. block.write_dir(&dir)?;
  1220. let meta_body = block.meta_body();
  1221. let block_path = meta_body.path().clone();
  1222. let parent_key = meta_body.block_key()?.clone();
  1223. (inode, block_path, parent_key)
  1224. };
  1225. block_path.push_component(name);
  1226. let (handle, stat) = {
  1227. let table_guard = self
  1228. .ensure_open(from, inode, block_path, Some(parent_key))
  1229. .await?;
  1230. let mut value_guard = table_guard.write(inode).await?;
  1231. let handle =
  1232. value_guard.new_handle(from.clone(), FlagValue::ReadWrite.into())?;
  1233. let stat = {
  1234. let mut block = value_guard.handle_guard_mut(from, handle).await?;
  1235. let stat = block.mut_meta_body().access_secrets(|secrets| {
  1236. secrets.block_id.generation = self.sb.generation;
  1237. secrets.block_id.inode = inode;
  1238. secrets.mode = mode & !umask;
  1239. if flags.directory() {
  1240. secrets.mode |= FileType::Dir.value();
  1241. } else {
  1242. secrets.mode |= FileType::Reg.value();
  1243. }
  1244. secrets.uid = authz_attrs.uid;
  1245. secrets.gid = authz_attrs.gid;
  1246. let now = Epoch::now();
  1247. secrets.atime = now;
  1248. secrets.ctime = now;
  1249. secrets.mtime = now;
  1250. secrets.nlink = 1;
  1251. Ok(secrets.to_owned())
  1252. })?;
  1253. if flags.directory() {
  1254. // Note that write_dir flushes data after writing, including
  1255. // metadata.
  1256. block.write_dir(&Directory::new())?;
  1257. } else {
  1258. block.flush_meta()?;
  1259. }
  1260. stat
  1261. };
  1262. if flags.directory() {
  1263. value_guard.convert_to_dir(handle)?;
  1264. }
  1265. value_guard.set_flags(handle, flags)?;
  1266. (handle, stat)
  1267. };
  1268. Ok(CreateReply {
  1269. inode,
  1270. handle,
  1271. entry: self.bt_entry(stat),
  1272. })
  1273. }
  1274. }
  1275. type OpenFut<'c> = impl 'c + Send + Future<Output = Result<OpenReply>>;
  1276. fn open<'c>(&'c self, from: &'c Arc<BlockPath>, msg: Open) -> Self::OpenFut<'c> {
  1277. async move {
  1278. let Open { inode, flags } = msg;
  1279. debug!("open: inode {inode}, flags {flags}");
  1280. if flags.value() & libc::O_APPEND != 0 {
  1281. return Err(Self::unsupported_flag_err("O_APPEND"));
  1282. }
  1283. if flags.value() & libc::O_CLOEXEC != 0 {
  1284. return Err(Self::unsupported_flag_err("O_CLOEXEC"));
  1285. }
  1286. let authz_attrs = self.authz_attrs(from).await?;
  1287. let handle = {
  1288. let table_guard = self.table_guard().await;
  1289. let mut value = table_guard.write(inode).await?;
  1290. let handle = value.new_handle(from.clone(), flags)?;
  1291. {
  1292. let block = {
  1293. let result = value.handle_guard(from, handle).await;
  1294. match result {
  1295. Ok(block) => block,
  1296. Err(ref err) => {
  1297. let message = err.to_string();
  1298. drop(result);
  1299. value.forget_handle(handle);
  1300. return Err(bterr!(message));
  1301. }
  1302. }
  1303. };
  1304. let ctx = AuthzContext::new(from, &authz_attrs, block.meta());
  1305. if flags.readable() {
  1306. if let Err(err) = self.authorizer.can_read(&ctx) {
  1307. drop(block);
  1308. value.forget_handle(handle);
  1309. return Err(err.into());
  1310. }
  1311. }
  1312. if flags.writeable() {
  1313. if let Err(err) = self.authorizer.can_write(&ctx) {
  1314. drop(block);
  1315. value.forget_handle(handle);
  1316. return Err(err.into());
  1317. }
  1318. }
  1319. }
  1320. if flags.directory() {
  1321. if let Err(err) = value.convert_to_dir(handle) {
  1322. value.forget_handle(handle);
  1323. return Err(err.into());
  1324. }
  1325. }
  1326. if let Err(err) = value.set_flags(handle, flags) {
  1327. value.forget_handle(handle);
  1328. return Err(err);
  1329. }
  1330. handle
  1331. };
  1332. Ok(OpenReply { handle })
  1333. }
  1334. }
  1335. type ReadGuard = BufGuard<C>;
  1336. type ReadFut<'c> = impl 'c + Send + Future<Output = Result<Self::ReadGuard>>;
  1337. fn read<'c>(&'c self, from: &'c Arc<BlockPath>, msg: Read) -> Self::ReadFut<'c> {
  1338. async move {
  1339. let Read {
  1340. inode,
  1341. handle,
  1342. offset,
  1343. size,
  1344. } = msg;
  1345. debug!("read: inode {inode}, handle {handle}, offset {offset}, size {size}");
  1346. BufGuard::new(self.inodes.clone(), from, inode, handle, offset, size).await
  1347. }
  1348. }
  1349. type WriteFut<'r> = impl 'r + Send + Future<Output = Result<WriteReply>>;
  1350. fn write<'c>(
  1351. &'c self,
  1352. from: &'c Arc<BlockPath>,
  1353. write: Write<&'c [u8]>,
  1354. ) -> Self::WriteFut<'c> {
  1355. async move {
  1356. let Write {
  1357. inode,
  1358. handle,
  1359. offset,
  1360. mut data,
  1361. } = write;
  1362. debug!("write: inode {inode}, handle {handle}, offset {offset}");
  1363. let table_guard = self.table_guard().await;
  1364. let mut value_guard = table_guard.write(inode).await?;
  1365. let mut block = value_guard.handle_guard_mut(from, handle).await?;
  1366. block.flags.assert_writeable()?;
  1367. let pos = block.pos() as u64;
  1368. if offset != pos {
  1369. block.seek(SeekFrom::Start(offset))?;
  1370. }
  1371. let written = std::io::copy(&mut data, block.deref_mut())?;
  1372. Ok(WriteReply { written })
  1373. }
  1374. }
  1375. type FlushFut<'c> = impl 'c + Send + Future<Output = Result<()>>;
  1376. fn flush<'c>(&'c self, from: &'c Arc<BlockPath>, msg: Flush) -> Self::FlushFut<'c> {
  1377. async move {
  1378. let Flush { inode, handle } = msg;
  1379. debug!("flush: inode {inode}, handle {handle}");
  1380. let table_guard = self.table_guard().await;
  1381. let mut value_guard = table_guard.write(inode).await?;
  1382. let mut handle_guard = match value_guard.handle_guard_mut(from, handle).await {
  1383. Ok(guard) => guard,
  1384. Err(err) => match err.downcast_ref::<Error>() {
  1385. Some(Error::ReadOnlyHandle(..)) => {
  1386. // We ignore attempts to flush read-only handles.
  1387. return Ok(());
  1388. }
  1389. _ => return Err(err),
  1390. },
  1391. };
  1392. handle_guard.flush()?;
  1393. Ok(())
  1394. }
  1395. }
  1396. type ReadDirFut<'c> = impl 'c + Send + Future<Output = Result<ReadDirReply>>;
  1397. fn read_dir<'c>(&'c self, from: &'c Arc<BlockPath>, msg: ReadDir) -> Self::ReadDirFut<'c> {
  1398. async move {
  1399. let ReadDir {
  1400. inode,
  1401. handle,
  1402. limit,
  1403. state,
  1404. } = msg;
  1405. debug!("read_dir: inode {inode}, handle {handle}, state {state}");
  1406. let table_guard = self.table_guard().await;
  1407. let value = table_guard.read(inode).await?;
  1408. let handle_value = value
  1409. .value(handle)
  1410. .map_err(|_| bterr!(Error::InvalidHandle { handle, inode }))?;
  1411. let (_, owner, flags) = handle_value.parts();
  1412. flags.assert_readable()?;
  1413. owner.assert_eq(from)?;
  1414. let dir = handle_value.directory()?;
  1415. let state: usize = state.try_into()?;
  1416. let server_limit = Self::READ_DIR_LIMIT.min(dir.num_entries() - state);
  1417. let entries_len = if limit > 0 {
  1418. server_limit.min(limit as usize)
  1419. } else {
  1420. server_limit
  1421. };
  1422. let pairs = dir
  1423. .entries()
  1424. .skip(state)
  1425. .take(entries_len)
  1426. .map(|(name, entry)| (name.to_owned(), entry.to_owned()));
  1427. let mut entries = Vec::with_capacity(entries_len);
  1428. entries.extend(pairs);
  1429. Ok(ReadDirReply {
  1430. entries,
  1431. new_state: (state + entries_len) as u64,
  1432. })
  1433. }
  1434. }
  1435. type LinkFut<'c> = impl 'c + Send + Future<Output = Result<LinkReply>>;
  1436. fn link<'c>(&'c self, from: &'c Arc<BlockPath>, msg: Link<'c>) -> Self::LinkFut<'c> {
  1437. async move {
  1438. let Link {
  1439. inode,
  1440. new_parent,
  1441. name,
  1442. } = msg;
  1443. debug!("link: inode {inode}, new_parent {new_parent}, name {name}");
  1444. let authz_attrs = self.authz_attrs(from).await?;
  1445. let table_guard = self.table_guard().await;
  1446. let mut value_guard = table_guard.write(new_parent).await?;
  1447. let parent_block = &mut value_guard.block;
  1448. self.authorizer.can_write(&AuthzContext::new(
  1449. from,
  1450. &authz_attrs,
  1451. parent_block.meta(),
  1452. ))?;
  1453. let mut dir = parent_block.read_dir()?;
  1454. if dir.contains_entry(name) {
  1455. return Err(io::Error::from_raw_os_error(libc::EEXIST).into());
  1456. }
  1457. let attr = {
  1458. let table_guard = self.table_guard().await;
  1459. let mut value = table_guard.write(inode).await?;
  1460. let block = value.block_mut();
  1461. let meta = block.mut_meta_body();
  1462. let attr = meta.access_secrets(|secrets| {
  1463. secrets.nlink += 1;
  1464. Ok(secrets.to_owned())
  1465. })?;
  1466. block.flush_meta()?;
  1467. value.incr_lookup_count(from);
  1468. attr
  1469. };
  1470. let file_type = FileType::from_value(attr.mode)?;
  1471. let entry = match file_type {
  1472. FileType::Reg => DirEntry::File(inode),
  1473. FileType::Dir => DirEntry::Directory(inode),
  1474. };
  1475. dir.insert_entry(name.to_owned(), entry);
  1476. parent_block.write_dir(&dir)?;
  1477. let entry = self.bt_entry(attr);
  1478. Ok(LinkReply { entry })
  1479. }
  1480. }
  1481. type UnlinkFut<'c> = impl 'c + Send + Future<Output = Result<()>>;
  1482. fn unlink<'c>(&'c self, from: &'c Arc<BlockPath>, msg: Unlink<'c>) -> Self::UnlinkFut<'c> {
  1483. fn decr_nlink(secrets: &mut BlockMetaSecrets) -> Result<u32> {
  1484. secrets.nlink -= 1;
  1485. Ok(secrets.nlink)
  1486. }
  1487. async move {
  1488. let Unlink { parent, name } = msg;
  1489. debug!("unlink: parent {parent}, name {name}");
  1490. let authz_attrs = self.authz_attrs(from).await?;
  1491. let (block_path, inode, parent_key) = {
  1492. let table_guard = self.table_guard().await;
  1493. let mut value_guard = table_guard.write(parent).await?;
  1494. let parent_block = &mut value_guard.block;
  1495. self.authorizer.can_write(&AuthzContext::new(
  1496. from,
  1497. &authz_attrs,
  1498. parent_block.meta(),
  1499. ))?;
  1500. let mut dir = parent_block.read_dir()?;
  1501. let entry = match dir.remove_entry(name) {
  1502. None => return Err(io::Error::from_raw_os_error(libc::ENOENT).into()),
  1503. Some(entry) => entry,
  1504. };
  1505. let inode = entry.inode();
  1506. parent_block.write_dir(&dir)?;
  1507. let meta_body = parent_block.meta_body();
  1508. let mut block_path = meta_body.path().clone();
  1509. block_path.push_component(name.to_owned());
  1510. let parent_key = meta_body.block_key()?.clone();
  1511. (block_path, inode, parent_key)
  1512. };
  1513. let table_guard = self.inodes.read().await;
  1514. let delete = if let Some(entry) = table_guard.get(&inode) {
  1515. let mut value = entry.write().await;
  1516. let nlink = value
  1517. .block_mut()
  1518. .mut_meta_body()
  1519. .access_secrets(decr_nlink)?;
  1520. value.delete = 0 == nlink;
  1521. // If the block is about to be deleted then there's no point in flushing its
  1522. // metadata.
  1523. if !value.delete {
  1524. value.block_mut().flush_meta()?;
  1525. }
  1526. // Since this block was already open, a client is keeping it alive. When they
  1527. // choose to forget this inode it will be deleted. Thus we return false here.
  1528. false
  1529. } else {
  1530. // It may be tempting to drop the table_guard here, but if this were done then
  1531. // another this block file could be opened concurrently.
  1532. let mut block = Self::open_block(
  1533. &self.path,
  1534. inode,
  1535. self.creds.clone(),
  1536. block_path,
  1537. Some(parent_key),
  1538. self.sb.inode_hash,
  1539. &self.sb.inode_key,
  1540. )?;
  1541. let nlink = block.mut_meta_body().access_secrets(decr_nlink)?;
  1542. if nlink > 0 {
  1543. block.flush_meta()?;
  1544. false
  1545. } else {
  1546. true
  1547. }
  1548. };
  1549. if delete {
  1550. self.delete_block_file(inode)?;
  1551. }
  1552. Ok(())
  1553. }
  1554. }
  1555. type ReadMetaFut<'c> = impl 'c + Send + Future<Output = Result<ReadMetaReply>>;
  1556. fn read_meta<'c>(
  1557. &'c self,
  1558. from: &'c Arc<BlockPath>,
  1559. msg: ReadMeta,
  1560. ) -> Self::ReadMetaFut<'c> {
  1561. async move {
  1562. let ReadMeta { inode, handle } = msg;
  1563. debug!("read_meta: inode {inode}, handle {:?}", handle);
  1564. let table_guard = self.table_guard().await;
  1565. let value_guard = table_guard.read(inode).await?;
  1566. let attrs = if let Some(handle) = handle {
  1567. let block = value_guard.handle_guard(from, handle).await?;
  1568. block.meta_body().secrets()?.to_owned()
  1569. } else {
  1570. value_guard.block().meta_body().secrets()?.to_owned()
  1571. };
  1572. debug!("read_meta attrs: {:?}", attrs);
  1573. let reply = ReadMetaReply {
  1574. attrs,
  1575. valid_for: self.attr_timeout(),
  1576. };
  1577. Ok(reply)
  1578. }
  1579. }
  1580. type WriteMetaFut<'c> = impl 'c + Send + Future<Output = Result<WriteMetaReply>>;
  1581. fn write_meta<'c>(
  1582. &'c self,
  1583. from: &'c Arc<BlockPath>,
  1584. msg: WriteMeta,
  1585. ) -> Self::WriteMetaFut<'c> {
  1586. async move {
  1587. let WriteMeta {
  1588. inode,
  1589. handle,
  1590. attrs,
  1591. attrs_set,
  1592. } = msg;
  1593. debug!("write_meta: inode {inode}, handle {:?}", handle);
  1594. let authz_attrs = self.authz_attrs(from).await?;
  1595. let cb = |block: &mut FileBlock<C>| {
  1596. self.authorizer.can_write(&AuthzContext::new(
  1597. from,
  1598. &authz_attrs,
  1599. block.meta(),
  1600. ))?;
  1601. let attrs = block.mut_meta_body().access_secrets(|secrets| {
  1602. if attrs_set.mode() {
  1603. secrets.mode = attrs.mode;
  1604. }
  1605. if attrs_set.uid() {
  1606. secrets.uid = attrs.uid;
  1607. }
  1608. if attrs_set.gid() {
  1609. secrets.gid = attrs.gid;
  1610. }
  1611. if attrs_set.atime() {
  1612. secrets.atime = attrs.atime;
  1613. }
  1614. if attrs_set.mtime() {
  1615. secrets.mtime = attrs.mtime;
  1616. }
  1617. if attrs_set.ctime() {
  1618. secrets.ctime = attrs.ctime;
  1619. }
  1620. for (key, value) in attrs.tags.into_iter() {
  1621. secrets.tags.insert(key, value);
  1622. }
  1623. Ok(secrets.to_owned())
  1624. })?;
  1625. block.flush_meta()?;
  1626. Ok::<_, btlib::Error>(attrs)
  1627. };
  1628. let attrs = {
  1629. let table_guard = self.table_guard().await;
  1630. let mut value_guard = table_guard.write(inode).await?;
  1631. if let Some(handle) = handle {
  1632. let mut block = value_guard.handle_guard_mut(from, handle).await?;
  1633. block.flags.assert_writeable()?;
  1634. cb(block.get_mut())
  1635. } else {
  1636. cb(value_guard.block.get_mut())
  1637. }
  1638. }?;
  1639. Ok(WriteMetaReply {
  1640. attrs,
  1641. valid_for: self.attr_timeout(),
  1642. })
  1643. }
  1644. }
  1645. type AllocateFut<'c> = impl 'c + Send + Future<Output = Result<()>>;
  1646. fn allocate<'c>(
  1647. &'c self,
  1648. from: &'c Arc<BlockPath>,
  1649. msg: Allocate,
  1650. ) -> Self::AllocateFut<'c> {
  1651. async move {
  1652. let Allocate {
  1653. inode,
  1654. handle,
  1655. offset,
  1656. size,
  1657. } = msg;
  1658. debug!(
  1659. "allocate: inode {inode}, handle {handle}, offset {:?}, size {size}",
  1660. offset
  1661. );
  1662. let table_guard = self.table_guard().await;
  1663. let mut value_guard = table_guard.write(inode).await?;
  1664. let mut block = value_guard.handle_guard_mut(from, handle).await?;
  1665. let curr_size = block.meta_body().secrets()?.size;
  1666. if let Some(offset) = offset {
  1667. if curr_size != offset {
  1668. return Err(bterr!("only allocations at the end of files are supported"));
  1669. }
  1670. }
  1671. let new_size = curr_size.max(size);
  1672. if new_size > curr_size {
  1673. block.zero_extend(new_size - curr_size)?;
  1674. }
  1675. Ok(())
  1676. }
  1677. }
  1678. type CloseFut<'c> = impl 'c + Send + Future<Output = Result<()>>;
  1679. fn close<'c>(&'c self, from: &'c Arc<BlockPath>, msg: Close) -> Self::CloseFut<'c> {
  1680. async move {
  1681. let Close { inode, handle } = msg;
  1682. debug!("close: inode {inode}, handle {handle}");
  1683. let table_guard = self.table_guard().await;
  1684. let mut value = table_guard.write(inode).await?;
  1685. match value.handle_guard_mut(from, handle).await {
  1686. Ok(mut block) => {
  1687. block.flush()?;
  1688. block.flush_meta()?;
  1689. }
  1690. Err(err) => match err.downcast_ref::<Error>() {
  1691. // If the cause of the error is that the handle is read-only, then it is
  1692. // not actually an error.
  1693. Some(Error::ReadOnlyHandle(_)) => (),
  1694. _ => return Err(err),
  1695. },
  1696. };
  1697. value.forget_handle(handle);
  1698. Ok(())
  1699. }
  1700. }
  1701. type ForgetFut<'c> = impl 'c + Send + Future<Output = Result<()>>;
  1702. fn forget<'c>(&'c self, from: &'c Arc<BlockPath>, msg: Forget) -> Self::ForgetFut<'c> {
  1703. async move {
  1704. let Forget { inode, count } = msg;
  1705. debug!("forget: inode {inode}, count {count}");
  1706. self.inode_forget(from.clone(), inode, count).await.bterr()
  1707. }
  1708. }
  1709. type LockFut<'c> = Ready<Result<()>>;
  1710. fn lock<'c>(&'c self, _from: &'c Arc<BlockPath>, _msg: Lock) -> Self::LockFut<'c> {
  1711. todo!();
  1712. }
  1713. type UnlockFut<'c> = Ready<Result<()>>;
  1714. fn unlock<'c>(&'c self, _from: &'c Arc<BlockPath>, _msg: Unlock) -> Self::UnlockFut<'c> {
  1715. todo!();
  1716. }
  1717. type AddReacapFut<'c> = impl 'c + Send + Future<Output = Result<()>>;
  1718. fn add_readcap<'c>(
  1719. &'c self,
  1720. from: &'c Arc<BlockPath>,
  1721. msg: AddReadcap,
  1722. ) -> Self::AddReacapFut<'c> {
  1723. async move {
  1724. let AddReadcap {
  1725. inode,
  1726. handle,
  1727. pub_creds,
  1728. } = msg;
  1729. debug!("add_readcap: inode {inode}, handle {handle}");
  1730. let table_guard = self.table_guard().await;
  1731. let mut value_guard = table_guard.write(inode).await?;
  1732. let mut block = value_guard.handle_guard_mut(from, handle).await?;
  1733. block.mut_meta_body().add_readcap_for(pub_creds)
  1734. }
  1735. }
  1736. type GrantAccessFut<'c> = impl 'c + Send + Future<Output = Result<()>>;
  1737. fn grant_access<'c>(
  1738. &'c self,
  1739. from: &'c Arc<BlockPath>,
  1740. msg: GrantAccess,
  1741. ) -> Self::GrantAccessFut<'c> {
  1742. let GrantAccess { inode, record } = msg;
  1743. debug!("grant_access: inode {inode}, record {:?}", record);
  1744. self.grant_access_to(from, inode, record)
  1745. }
  1746. }
  1747. }