1use crate::{
3 Error, Result,
4 context::{HostContext, validate_absolute},
5 error::io_error,
6};
7use rustix::fs::{self, Mode, OFlags};
8use std::{
9 fs::{File, TryLockError},
10 io::{Read, Write},
11 os::unix::fs::{MetadataExt, PermissionsExt},
12 path::{Component, Path, PathBuf},
13 sync::atomic::{AtomicU64, Ordering},
14};
15
16pub(crate) struct PrivateDir {
17 pub(crate) file: File,
18 pub(crate) path: PathBuf,
19}
20
21impl PrivateDir {
22 pub(crate) fn open(path: &Path, create: bool) -> Result<Option<Self>> {
23 validate_absolute(path)?;
24 let mut directory: File = fs::open(
25 "/",
26 OFlags::RDONLY | OFlags::DIRECTORY | OFlags::CLOEXEC,
27 Mode::empty(),
28 )
29 .map(File::from)
30 .map_err(|e| io_error("open filesystem root", "/", e))?;
31 let mut walked = PathBuf::from("/");
32 for component in path.components() {
33 let Component::Normal(name) = component else {
34 continue;
35 };
36 walked.push(name);
37 let flags = OFlags::RDONLY | OFlags::DIRECTORY | OFlags::NOFOLLOW | OFlags::CLOEXEC;
38 let next = match fs::openat(&directory, name, flags, Mode::empty()) {
39 Ok(fd) => fd,
40 Err(rustix::io::Errno::NOENT) if create => {
41 match fs::mkdirat(&directory, name, Mode::RUSR | Mode::WUSR | Mode::XUSR) {
42 Ok(()) | Err(rustix::io::Errno::EXIST) => {}
43 Err(e) => return Err(io_error("create private directory", &walked, e)),
44 }
45 directory
46 .sync_all()
47 .map_err(|e| io_error("sync directory parent", &walked, e))?;
48 fs::openat(&directory, name, flags, Mode::empty())
49 .map_err(|e| io_error("open private directory", &walked, e))?
50 }
51 Err(rustix::io::Errno::NOENT) => return Ok(None),
52 Err(e) => {
53 return Err(io_error(
54 "open state directory without following symlinks",
55 &walked,
56 e,
57 ));
58 }
59 };
60 directory = File::from(next);
61 }
62 let metadata = directory
63 .metadata()
64 .map_err(|e| io_error("inspect private directory", path, e))?;
65 if metadata.uid() != rustix::process::geteuid().as_raw()
66 || metadata.permissions().mode() & 0o077 != 0
67 {
68 return Err(Error::Invalid(format!(
69 "private directory must be owned by this user with mode 0700: {}",
70 path.display()
71 )));
72 }
73 Ok(Some(Self {
74 file: directory,
75 path: path.to_owned(),
76 }))
77 }
78
79 pub(crate) fn check_file(&self, file: &File, name: &str) -> Result<()> {
80 let metadata = file
81 .metadata()
82 .map_err(|e| io_error("inspect state file", self.path.join(name), e))?;
83 if !metadata.is_file()
84 || metadata.nlink() != 1
85 || metadata.uid() != rustix::process::geteuid().as_raw()
86 || metadata.permissions().mode() & 0o077 != 0
87 {
88 return Err(Error::Invalid(format!(
89 "state file must be a private, owned regular file without hard links: {}",
90 self.path.join(name).display()
91 )));
92 }
93 Ok(())
94 }
95
96 pub(crate) fn read(&self, name: &str) -> Result<Option<String>> {
97 let fd = match fs::openat(
98 &self.file,
99 name,
100 OFlags::RDONLY | OFlags::NOFOLLOW | OFlags::CLOEXEC | OFlags::NONBLOCK,
101 Mode::empty(),
102 ) {
103 Ok(fd) => fd,
104 Err(rustix::io::Errno::NOENT) => return Ok(None),
105 Err(e) => return Err(io_error("open state file", self.path.join(name), e)),
106 };
107 let mut file = File::from(fd);
108 self.check_file(&file, name)?;
109 let mut text = String::new();
110 file.read_to_string(&mut text)
111 .map_err(|e| io_error("read state file", self.path.join(name), e))?;
112 Ok(Some(text))
113 }
114
115 pub(crate) fn create(&self, name: &str, content: &[u8]) -> Result<()> {
117 let mut file = File::from(
118 fs::openat(
119 &self.file,
120 name,
121 OFlags::WRONLY | OFlags::CREATE | OFlags::EXCL | OFlags::NOFOLLOW | OFlags::CLOEXEC,
122 Mode::RUSR | Mode::WUSR,
123 )
124 .map_err(|e| io_error("create immutable state file", self.path.join(name), e))?,
125 );
126 self.check_file(&file, name)?;
127 file.write_all(content)
128 .map_err(|e| io_error("write immutable state file", self.path.join(name), e))?;
129 file.sync_all()
130 .map_err(|e| io_error("sync immutable state file", self.path.join(name), e))?;
131 self.sync()
132 }
133
134 pub(crate) fn sync(&self) -> Result<()> {
135 self.file
136 .sync_all()
137 .map_err(|e| io_error("sync private directory", &self.path, e))
138 }
139
140 pub(crate) fn replace(&self, name: &str, content: &str) -> Result<()> {
141 static NEXT: AtomicU64 = AtomicU64::new(0);
142 let mut created = None;
143 for _ in 0..100 {
144 let temporary = format!(
145 ".{name}.{}.{}.tmp",
146 std::process::id(),
147 NEXT.fetch_add(1, Ordering::Relaxed)
148 );
149 match fs::openat(
150 &self.file,
151 temporary.as_str(),
152 OFlags::WRONLY | OFlags::CREATE | OFlags::EXCL | OFlags::NOFOLLOW | OFlags::CLOEXEC,
153 Mode::RUSR | Mode::WUSR,
154 ) {
155 Ok(fd) => {
156 created = Some((temporary, File::from(fd)));
157 break;
158 }
159 Err(rustix::io::Errno::EXIST) => continue,
160 Err(e) => {
161 return Err(io_error(
162 "create state replacement",
163 self.path.join(name),
164 e,
165 ));
166 }
167 }
168 }
169 let (temporary, mut file) = created
170 .ok_or_else(|| Error::Invalid("could not allocate state replacement file".into()))?;
171 let result = (|| {
172 file.write_all(content.as_bytes())
173 .map_err(|e| io_error("write state replacement", self.path.join(name), e))?;
174 file.sync_all()
175 .map_err(|e| io_error("sync state replacement", self.path.join(name), e))?;
176 fs::renameat(&self.file, temporary.as_str(), &self.file, name)
177 .map_err(|e| io_error("replace state file", self.path.join(name), e))?;
178 self.file
179 .sync_all()
180 .map_err(|e| io_error("sync state directory", &self.path, e))?;
181 Ok(())
182 })();
183 if result.is_err() {
184 let _ = fs::unlinkat(&self.file, temporary.as_str(), fs::AtFlags::empty());
185 }
186 result
187 }
188}
189
190pub struct WriterLock {
192 _file: File,
193 config_dir: PathBuf,
194 state_dir: PathBuf,
195}
196
197impl WriterLock {
198 pub fn acquire(host: &HostContext) -> Result<Self> {
199 let directory = PrivateDir::open(&host.state_dir, true)?.expect("created state directory");
200 let file = fs::openat(
201 &directory.file,
202 "lock",
203 OFlags::RDWR | OFlags::CREATE | OFlags::NOFOLLOW | OFlags::CLOEXEC | OFlags::NONBLOCK,
204 Mode::RUSR | Mode::WUSR,
205 )
206 .map(File::from)
207 .map_err(|e| io_error("open application lock", host.state_dir.join("lock"), e))?;
208 directory.check_file(&file, "lock")?;
209 match file.try_lock() {
210 Ok(()) => Ok(Self {
211 _file: file,
212 config_dir: host.config_dir.clone(),
213 state_dir: host.state_dir.clone(),
214 }),
215 Err(TryLockError::WouldBlock) => Err(Error::Locked),
216 Err(TryLockError::Error(e)) => Err(io_error(
217 "acquire application lock",
218 host.state_dir.join("lock"),
219 e,
220 )),
221 }
222 }
223
224 pub(crate) fn check_context(&self, host: &HostContext) -> Result<()> {
225 if self.config_dir != host.config_dir || self.state_dir != host.state_dir {
226 return Err(Error::Invalid(
227 "writer lock belongs to a different host context".into(),
228 ));
229 }
230 Ok(())
231 }
232}