synapse
A component of the AienOS ecosystem.
Brought by drakestapleton
synapse / crates / synapse-coord / src / record.rs
| 1 | //! Bounded, non-blocking reads of store files (issue #58). |
| 2 | //! |
| 3 | //! Anyone who can write into the shared coordination store can plant a FIFO, a device, a |
| 4 | //! symlink to `/dev/zero`, or a huge file under a record name. A plain `fs::read` blocks |
| 5 | //! forever on the first and reads without limit on the others, so one hostile entry would |
| 6 | //! stop every reader (and the pre-submit advisory, which must always answer). Every store |
| 7 | //! file read goes through [`read_bounded`] instead: |
| 8 | //! |
| 9 | //! 1. `lstat` the name; anything that is not a regular file is refused without opening it |
| 10 | //! (a FIFO, socket or device is never opened, so opening can have no side effect); |
| 11 | //! 2. open with `O_NOFOLLOW | O_NONBLOCK | O_CLOEXEC` (a symlink swapped in after step 1 |
| 12 | //! fails with `ELOOP`; a FIFO swapped in cannot block the open); |
| 13 | //! 3. `fstat` the opened descriptor and refuse anything that is not a regular file; |
| 14 | //! 4. read at most `cap + 1` bytes and refuse the record if more than `cap` arrive. |
| 15 | //! |
| 16 | //! A refusal is a typed [`CoordError::RefusedRecord`], handled exactly like |
| 17 | //! [`CoordError::CorruptRecord`]: the operation fails, nothing is written, the file is left |
| 18 | //! as found, and the read-only advisory reports `Unavailable`. |
| 19 | |
| 20 | use crate::CoordError; |
| 21 | use std::fs::{self, File, OpenOptions}; |
| 22 | use std::io::Read; |
| 23 | use std::os::unix::fs::{FileTypeExt, OpenOptionsExt}; |
| 24 | use std::path::Path; |
| 25 | |
| 26 | /// Largest coordination record (`dirs/*.json`, `agents/*.json`) that is read: 1 MiB. |
| 27 | /// crumb.c records are a few KiB (20 history entries, locks, whispers of the last 24 h). |
| 28 | /// A record that would exceed this is refused on write as well, so this crate never creates |
| 29 | /// a record it would later refuse to read. |
| 30 | pub const MAX_RECORD_BYTES: u64 = 1 << 20; |
| 31 | |
| 32 | /// Largest `STORE_ID` marker that is read. A v1 marker is under 100 bytes. |
| 33 | pub const MAX_MARKER_BYTES: u64 = 4096; |
| 34 | |
| 35 | /// Why a store file was refused without being parsed. |
| 36 | #[derive(Debug, Clone, PartialEq, Eq)] |
| 37 | pub enum RecordRefusal { |
| 38 | /// The name is a symbolic link. Records are never followed (crumb.c follows them; a |
| 39 | /// link to `/dev/zero` or a FIFO elsewhere would stall every reader). |
| 40 | Symlink, |
| 41 | /// The name is not a regular file: `"fifo"`, `"socket"`, `"char device"`, |
| 42 | /// `"block device"` or `"directory"`. |
| 43 | NotRegular(&'static str), |
| 44 | /// The file is larger than `limit` bytes. |
| 45 | TooLarge { limit: u64 }, |
| 46 | /// A directory component of a record path is not a directory (for example a regular |
| 47 | /// file planted where a subdirectory of `dirs/` is expected). |
| 48 | NotDirectory, |
| 49 | } |
| 50 | |
| 51 | impl std::fmt::Display for RecordRefusal { |
| 52 | fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { |
| 53 | match self { |
| 54 | RecordRefusal::Symlink => write!(f, "is a symbolic link"), |
| 55 | RecordRefusal::NotRegular(k) => write!(f, "is a {k}, not a regular file"), |
| 56 | RecordRefusal::TooLarge { limit } => write!(f, "is larger than {limit} bytes"), |
| 57 | RecordRefusal::NotDirectory => write!(f, "is not a directory"), |
| 58 | } |
| 59 | } |
| 60 | } |
| 61 | |
| 62 | pub(crate) fn refusal_for(ft: &fs::FileType) -> Option<RecordRefusal> { |
| 63 | if ft.is_file() { |
| 64 | None |
| 65 | } else if ft.is_symlink() { |
| 66 | Some(RecordRefusal::Symlink) |
| 67 | } else if ft.is_fifo() { |
| 68 | Some(RecordRefusal::NotRegular("fifo")) |
| 69 | } else if ft.is_socket() { |
| 70 | Some(RecordRefusal::NotRegular("socket")) |
| 71 | } else if ft.is_char_device() { |
| 72 | Some(RecordRefusal::NotRegular("char device")) |
| 73 | } else if ft.is_block_device() { |
| 74 | Some(RecordRefusal::NotRegular("block device")) |
| 75 | } else if ft.is_dir() { |
| 76 | Some(RecordRefusal::NotRegular("directory")) |
| 77 | } else { |
| 78 | Some(RecordRefusal::NotRegular("special file")) |
| 79 | } |
| 80 | } |
| 81 | |
| 82 | fn refused(path: &Path, reason: RecordRefusal) -> CoordError { |
| 83 | CoordError::RefusedRecord { |
| 84 | path: path.to_path_buf(), |
| 85 | reason, |
| 86 | } |
| 87 | } |
| 88 | |
| 89 | fn io(path: &Path, source: std::io::Error) -> CoordError { |
| 90 | CoordError::Io { |
| 91 | path: path.to_path_buf(), |
| 92 | source, |
| 93 | } |
| 94 | } |
| 95 | |
| 96 | /// Read a store file of at most `cap` bytes without following links or blocking. |
| 97 | /// `Ok(None)` when the name does not exist. |
| 98 | pub(crate) fn read_bounded(path: &Path, cap: u64) -> Result<Option<Vec<u8>>, CoordError> { |
| 99 | match fs::symlink_metadata(path) { |
| 100 | Ok(m) => { |
| 101 | if let Some(r) = refusal_for(&m.file_type()) { |
| 102 | return Err(refused(path, r)); |
| 103 | } |
| 104 | } |
| 105 | Err(e) if e.kind() == std::io::ErrorKind::NotFound => return Ok(None), |
| 106 | Err(e) => return Err(io(path, e)), |
| 107 | } |
| 108 | let f = match OpenOptions::new() |
| 109 | .read(true) |
| 110 | .custom_flags(libc::O_NOFOLLOW | libc::O_NONBLOCK | libc::O_CLOEXEC) |
| 111 | .open(path) |
| 112 | { |
| 113 | Ok(f) => f, |
| 114 | Err(e) if e.kind() == std::io::ErrorKind::NotFound => return Ok(None), |
| 115 | Err(e) if e.raw_os_error() == Some(libc::ELOOP) => { |
| 116 | return Err(refused(path, RecordRefusal::Symlink)) |
| 117 | } |
| 118 | Err(e) => return Err(io(path, e)), |
| 119 | }; |
| 120 | let m = f.metadata().map_err(|e| io(path, e))?; |
| 121 | if let Some(r) = refusal_for(&m.file_type()) { |
| 122 | return Err(refused(path, r)); |
| 123 | } |
| 124 | if m.len() > cap { |
| 125 | return Err(refused(path, RecordRefusal::TooLarge { limit: cap })); |
| 126 | } |
| 127 | let mut buf = Vec::with_capacity(m.len() as usize); |
| 128 | (&f as &File) |
| 129 | .take(cap + 1) |
| 130 | .read_to_end(&mut buf) |
| 131 | .map_err(|e| io(path, e))?; |
| 132 | if buf.len() as u64 > cap { |
| 133 | return Err(refused(path, RecordRefusal::TooLarge { limit: cap })); |
| 134 | } |
| 135 | Ok(Some(buf)) |
| 136 | } |
| 137 | |
| 138 | /// Whether the test-only fault list names this path. `SYNAPSE_COORD_FAULT` (the variable |
| 139 | /// of every other fault point of this crate, unset in normal use) is read as a |
| 140 | /// comma-separated list; an item `<kind>:<name>` with one of `kinds` matches a path whose |
| 141 | /// final component is exactly `<name>`. |
| 142 | fn fault_names(kinds: &[&str], p: &Path) -> bool { |
| 143 | let Ok(v) = std::env::var("SYNAPSE_COORD_FAULT") else { |
| 144 | return false; |
| 145 | }; |
| 146 | let Some(name) = p.file_name().and_then(|n| n.to_str()) else { |
| 147 | return false; |
| 148 | }; |
| 149 | v.split(',').any(|item| { |
| 150 | item.split_once(':') |
| 151 | .is_some_and(|(k, n)| n == name && kinds.contains(&k)) |
| 152 | }) |
| 153 | } |
| 154 | |
| 155 | fn injected_eio() -> std::io::Error { |
| 156 | std::io::Error::from_raw_os_error(libc::EIO) |
| 157 | } |
| 158 | |
| 159 | /// `lstat` for a lookup whose answer decides what an operation may do (a marker, a |
| 160 | /// discriminator file, a journal that may be missing). Test-only fault injection: |
| 161 | /// `SYNAPSE_COORD_FAULT=stat-eio:<name>` makes the lookup of a path named `<name>` fail |
| 162 | /// with `EIO`; `marker-stat-eio:<name>` (the round-13 spelling) is the same point. |
| 163 | pub(crate) fn lstat(p: &Path) -> std::io::Result<fs::Metadata> { |
| 164 | if fault_names(&["stat-eio", "marker-stat-eio"], p) { |
| 165 | return Err(injected_eio()); |
| 166 | } |
| 167 | fs::symlink_metadata(p) |
| 168 | } |
| 169 | |
| 170 | /// `read_dir` for a listing whose completeness decides what an operation may do. |
| 171 | /// Test-only fault injection: `SYNAPSE_COORD_FAULT=readdir-eio:<name>` makes listing a |
| 172 | /// directory named `<name>` fail with `EIO`; `readdirent-eio:<name>` lists every real |
| 173 | /// entry and then yields one entry error (`EIO`), as a failing `getdents` would. |
| 174 | pub(crate) fn list_dir( |
| 175 | dir: &Path, |
| 176 | ) -> std::io::Result<impl Iterator<Item = std::io::Result<fs::DirEntry>>> { |
| 177 | if fault_names(&["readdir-eio"], dir) { |
| 178 | return Err(injected_eio()); |
| 179 | } |
| 180 | let rd = fs::read_dir(dir)?; |
| 181 | let tail = fault_names(&["readdirent-eio"], dir).then(injected_eio); |
| 182 | Ok(rd.chain(tail.map(Err))) |
| 183 | } |
| 184 | |
| 185 | /// Refuse to replace `path` unless it is absent or a regular file (a rename would silently |
| 186 | /// swap a planted FIFO or symlink for a record; refuse instead, like a corrupt record). |
| 187 | pub(crate) fn check_replaceable(path: &Path) -> Result<(), CoordError> { |
| 188 | match fs::symlink_metadata(path) { |
| 189 | Ok(m) => match refusal_for(&m.file_type()) { |
| 190 | Some(r) => Err(refused(path, r)), |
| 191 | None => Ok(()), |
| 192 | }, |
| 193 | Err(e) if e.kind() == std::io::ErrorKind::NotFound => Ok(()), |
| 194 | Err(e) => Err(io(path, e)), |
| 195 | } |
| 196 | } |
| 197 | |
| 198 | /// Create a fresh temporary file for a durable write. Whatever already has that name (a |
| 199 | /// stale temp from a crashed writer with the same pid, or a planted FIFO or symlink) is |
| 200 | /// unlinked first, never opened, and the new file is created with `O_EXCL | O_NOFOLLOW`, so |
| 201 | /// the write can neither block on a FIFO nor follow a link to somewhere else. |
| 202 | pub(crate) fn create_temp(tmp: &Path) -> Result<File, CoordError> { |
| 203 | match fs::remove_file(tmp) { |
| 204 | Ok(()) => {} |
| 205 | Err(e) if e.kind() == std::io::ErrorKind::NotFound => {} |
| 206 | Err(e) => return Err(io(tmp, e)), |
| 207 | } |
| 208 | OpenOptions::new() |
| 209 | .write(true) |
| 210 | .create_new(true) |
| 211 | .mode(0o644) |
| 212 | .custom_flags(libc::O_NOFOLLOW | libc::O_CLOEXEC) |
| 213 | .open(tmp) |
| 214 | .map_err(|e| io(tmp, e)) |
| 215 | } |
| 216 | |
| 217 | /// Refuse a record path whose directory components below `root` are not all real |
| 218 | /// directories. Every existing component from `root` (exclusive) down to `path`'s parent is |
| 219 | /// checked with `lstat`: a symbolic link is refused (a write would otherwise land outside the |
| 220 | /// store, and a read would load a record the listing never shows, since listing does not |
| 221 | /// follow symlinked directories), and anything else that is not a directory is refused as |
| 222 | /// not regular. Components that do not exist yet are fine; they are created as real |
| 223 | /// directories by the writer. A path outside `root` is refused as a symlink escape. |
| 224 | pub(crate) fn check_real_parents(root: &Path, path: &Path) -> Result<(), CoordError> { |
| 225 | let parent = path.parent().unwrap_or(Path::new("")); |
| 226 | let rel = parent |
| 227 | .strip_prefix(root) |
| 228 | .map_err(|_| refused(path, RecordRefusal::Symlink))?; |
| 229 | let mut cur = root.to_path_buf(); |
| 230 | for comp in rel.components() { |
| 231 | cur.push(comp); |
| 232 | match fs::symlink_metadata(&cur) { |
| 233 | Ok(m) => { |
| 234 | let ft = m.file_type(); |
| 235 | if ft.is_symlink() { |
| 236 | return Err(refused(&cur, RecordRefusal::Symlink)); |
| 237 | } |
| 238 | if !ft.is_dir() { |
| 239 | return Err(refused(&cur, RecordRefusal::NotDirectory)); |
| 240 | } |
| 241 | } |
| 242 | Err(e) if e.kind() == std::io::ErrorKind::NotFound => return Ok(()), |
| 243 | Err(e) => return Err(io(&cur, e)), |
| 244 | } |
| 245 | } |
| 246 | Ok(()) |
| 247 | } |
| 248 | |
| 249 | /// Read a store record file (at most [`MAX_RECORD_BYTES`]) without following a final |
| 250 | /// symbolic link or blocking on a FIFO; `Ok(None)` when it does not exist. For tools such |
| 251 | /// as the `synapse-coord canon` command, which must not trust the file they are given. |
| 252 | pub fn read_record_file(path: &Path) -> Result<Option<Vec<u8>>, CoordError> { |
| 253 | read_bounded(path, MAX_RECORD_BYTES) |
| 254 | } |