| 1 | use crate::{ |
| 2 | archive::{self, Member, MetadataBudget}, |
| 3 | filesystem, |
| 4 | protocol::*, |
| 5 | }; |
| 6 | use std::{ |
| 7 | fs::{self, File, Metadata}, |
| 8 | path::{Component, Path, PathBuf}, |
| 9 | time::SystemTime, |
| 10 | }; |
| 11 | |
| 12 | type Result<T> = std::result::Result<T, ErrorCode>; |
| 13 | |
| 14 | pub(super) struct Input { |
| 15 | pub file: File, |
| 16 | #[cfg(windows)] |
| 17 | _parents: Vec<File>, |
| 18 | } |
| 19 | impl Input { |
| 20 | #[cfg(target_os = "linux")] |
| 21 | fn child(file: &File, name: &std::ffi::OsStr) -> Result<File> { |
| 22 | use std::os::{ |
| 23 | fd::{AsRawFd, FromRawFd}, |
| 24 | unix::ffi::OsStrExt, |
| 25 | }; |
| 26 | unsafe extern "C" { |
| 27 | fn openat(fd: i32, name: *const i8, flags: i32, ...) -> i32; |
| 28 | } |
| 29 | let name = std::ffi::CString::new(name.as_bytes()).map_err(|_| ErrorCode::UnsafePath)?; |
| 30 | // 링크를 따라가지 않는 경로 핸들로 객체 종류를 확인함. |
| 31 | let fd = unsafe { |
| 32 | openat( |
| 33 | file.as_raw_fd(), |
| 34 | name.as_ptr(), |
| 35 | 0x80000 | 0x20000 | 0x200000, |
| 36 | ) |
| 37 | }; |
| 38 | if fd < 0 { |
| 39 | let error = std::io::Error::last_os_error(); |
| 40 | return Err(if matches!(error.raw_os_error(), Some(20 | 40)) { |
| 41 | ErrorCode::UnsafePath |
| 42 | } else { |
| 43 | crate::space::io_error(error) |
| 44 | }); |
| 45 | } |
| 46 | let pinned = unsafe { File::from_raw_fd(fd) }; |
| 47 | Self::validate(&pinned)?; |
| 48 | Ok(pinned) |
| 49 | } |
| 50 | #[cfg(target_os = "linux")] |
| 51 | fn read(pinned: File) -> Result<File> { |
| 52 | use std::os::fd::AsRawFd; |
| 53 | // 읽기 권한은 최종 입력에만 요청함. |
| 54 | File::open(format!("/proc/self/fd/{}", pinned.as_raw_fd())).map_err(crate::space::io_error) |
| 55 | } |
| 56 | pub fn open(path: &Path) -> Result<Self> { |
| 57 | if !path.is_absolute() { |
| 58 | return Err(ErrorCode::InvalidRequest); |
| 59 | } |
| 60 | #[cfg(target_os = "linux")] |
| 61 | { |
| 62 | use std::os::unix::fs::OpenOptionsExt; |
| 63 | let mut file = fs::OpenOptions::new() |
| 64 | .read(true) |
| 65 | .custom_flags(0x200000 | 0x20000 | 0x10000 | 0x80000) |
| 66 | .open("/") |
| 67 | .map_err(crate::space::io_error)?; |
| 68 | for part in path.components() { |
| 69 | match part { |
| 70 | Component::RootDir => {} |
| 71 | Component::Normal(name) => file = Self::child(&file, name)?, |
| 72 | _ => return Err(ErrorCode::UnsafePath), |
| 73 | } |
| 74 | } |
| 75 | let file = Self::read(file)?; |
| 76 | Self::validate(&file)?; |
| 77 | Ok(Self { file }) |
| 78 | } |
| 79 | #[cfg(windows)] |
| 80 | { |
| 81 | use std::os::windows::fs::OpenOptionsExt; |
| 82 | let mut current = PathBuf::new(); |
| 83 | let mut parents = Vec::new(); |
| 84 | for part in path.components() { |
| 85 | match part { |
| 86 | Component::Prefix(_) | Component::RootDir => current.push(part.as_os_str()), |
| 87 | Component::Normal(name) => { |
| 88 | if parents.is_empty() { |
| 89 | parents.push(Self::lock(¤t)?); |
| 90 | } |
| 91 | current.push(name); |
| 92 | parents.push(Self::lock(¤t)?); |
| 93 | } |
| 94 | _ => return Err(ErrorCode::UnsafePath), |
| 95 | } |
| 96 | } |
| 97 | let file = fs::OpenOptions::new() |
| 98 | .read(true) |
| 99 | .share_mode(1) |
| 100 | .custom_flags(0x02000000 | 0x00200000) |
| 101 | .open(¤t) |
| 102 | .map_err(crate::space::io_error)?; |
| 103 | Self::validate(&file)?; |
| 104 | Ok(Self { |
| 105 | file, |
| 106 | _parents: parents, |
| 107 | }) |
| 108 | } |
| 109 | } |
| 110 | #[cfg(windows)] |
| 111 | fn lock(path: &Path) -> Result<File> { |
| 112 | use std::os::windows::fs::{MetadataExt, OpenOptionsExt}; |
| 113 | let file = fs::OpenOptions::new() |
| 114 | .access_mode(0) |
| 115 | .share_mode(3) |
| 116 | .custom_flags(0x02000000 | 0x00200000) |
| 117 | .open(path) |
| 118 | .map_err(crate::space::io_error)?; |
| 119 | if file |
| 120 | .metadata() |
| 121 | .map_err(crate::space::io_error)? |
| 122 | .file_attributes() |
| 123 | & 0x400 |
| 124 | != 0 |
| 125 | { |
| 126 | return Err(ErrorCode::UnsafePath); |
| 127 | } |
| 128 | Ok(file) |
| 129 | } |
| 130 | fn validate(file: &File) -> Result<()> { |
| 131 | let metadata = file.metadata().map_err(crate::space::io_error)?; |
| 132 | #[cfg(windows)] |
| 133 | { |
| 134 | use std::os::windows::fs::MetadataExt; |
| 135 | if metadata.file_attributes() & 0x400 != 0 { |
| 136 | return Err(ErrorCode::UnsafePath); |
| 137 | } |
| 138 | } |
| 139 | if !metadata.is_dir() && !metadata.is_file() { |
| 140 | return Err(ErrorCode::UnsafePath); |
| 141 | } |
| 142 | Ok(()) |
| 143 | } |
| 144 | fn open_child(&self, path: &Path, name: &str) -> Result<Self> { |
| 145 | #[cfg(target_os = "linux")] |
| 146 | { |
| 147 | let _ = path; |
| 148 | let file = Self::read(Self::child(&self.file, std::ffi::OsStr::new(name))?)?; |
| 149 | Self::validate(&file)?; |
| 150 | Ok(Self { file }) |
| 151 | } |
| 152 | #[cfg(windows)] |
| 153 | { |
| 154 | Self::open(&path.join(name)) |
| 155 | } |
| 156 | } |
| 157 | fn children(&self, path: &Path) -> Result<fs::ReadDir> { |
| 158 | #[cfg(target_os = "linux")] |
| 159 | { |
| 160 | use std::os::fd::AsRawFd; |
| 161 | let _ = path; |
| 162 | fs::read_dir(format!("/proc/self/fd/{}", self.file.as_raw_fd())) |
| 163 | .map_err(crate::space::io_error) |
| 164 | } |
| 165 | #[cfg(windows)] |
| 166 | { |
| 167 | fs::read_dir(path).map_err(crate::space::io_error) |
| 168 | } |
| 169 | } |
| 170 | } |
| 171 | |
| 172 | pub(super) struct Planned { |
| 173 | pub member: Member, |
| 174 | path: PathBuf, |
| 175 | object: SourceObject, |
| 176 | modified: Option<SystemTime>, |
| 177 | } |
| 178 | impl Planned { |
| 179 | pub fn open(&self) -> Result<Input> { |
| 180 | let input = Input::open(&self.path).map_err(|_| ErrorCode::SourceChanged)?; |
| 181 | if !self.matches(&input.file)? { |
| 182 | return Err(ErrorCode::SourceChanged); |
| 183 | } |
| 184 | Ok(input) |
| 185 | } |
| 186 | fn matches(&self, file: &File) -> Result<bool> { |
| 187 | let metadata = file.metadata().map_err(crate::space::io_error)?; |
| 188 | Ok(filesystem::object(file)? == self.object |
| 189 | && metadata.modified().ok() == self.modified |
| 190 | && metadata.is_dir() == (self.member.entry.kind == EntryKind::Directory) |
| 191 | && (metadata.is_dir() || metadata.len() == self.member.entry.size)) |
| 192 | } |
| 193 | } |
| 194 | pub(super) struct Plan { |
| 195 | pub items: Vec<Planned>, |
| 196 | limits: Limits, |
| 197 | budget: MetadataBudget, |
| 198 | total: u64, |
| 199 | } |
| 200 | impl Plan { |
| 201 | pub fn new( |
| 202 | sources: &[Source], |
| 203 | limits: Limits, |
| 204 | check: &mut impl FnMut() -> Result<()>, |
| 205 | ) -> Result<Self> { |
| 206 | if sources.len() > limits.entries as usize { |
| 207 | return Err(ErrorCode::Limit); |
| 208 | } |
| 209 | let mut plan = Self { |
| 210 | items: Vec::new(), |
| 211 | limits, |
| 212 | budget: MetadataBudget::default(), |
| 213 | total: 0, |
| 214 | }; |
| 215 | let mut roots = std::collections::BTreeSet::new(); |
| 216 | for source in sources { |
| 217 | check()?; |
| 218 | let name = archive::valid_name(&source.archive_name, false)?; |
| 219 | if !roots.insert(name.to_lowercase()) { |
| 220 | return Err(ErrorCode::Conflict); |
| 221 | } |
| 222 | } |
| 223 | for source in sources { |
| 224 | let path = source.path.to_path()?; |
| 225 | let input = Input::open(&path)?; |
| 226 | plan.visit(path, source.archive_name.clone(), input, check)?; |
| 227 | } |
| 228 | let members = plan |
| 229 | .items |
| 230 | .iter() |
| 231 | .map(|p| Member { |
| 232 | entry: p.member.entry.clone(), |
| 233 | data: Vec::new(), |
| 234 | }) |
| 235 | .collect::<Vec<_>>(); |
| 236 | archive::validate_members(&members)?; |
| 237 | Ok(plan) |
| 238 | } |
| 239 | fn visit( |
| 240 | &mut self, |
| 241 | path: PathBuf, |
| 242 | name: String, |
| 243 | input: Input, |
| 244 | check: &mut impl FnMut() -> Result<()>, |
| 245 | ) -> Result<()> { |
| 246 | check()?; |
| 247 | if self.items.len() >= self.limits.entries as usize { |
| 248 | return Err(ErrorCode::Limit); |
| 249 | } |
| 250 | let metadata: Metadata = input.file.metadata().map_err(crate::space::io_error)?; |
| 251 | let directory = metadata.is_dir(); |
| 252 | let name = archive::valid_name(&name, directory)?; |
| 253 | self.budget.charge(&name)?; |
| 254 | self.budget.charge(&path.to_string_lossy())?; |
| 255 | let size = if directory { 0 } else { metadata.len() }; |
| 256 | self.total = self |
| 257 | .total |
| 258 | .checked_add(size) |
| 259 | .filter(|n| *n <= self.limits.input.min(self.limits.output)) |
| 260 | .ok_or(ErrorCode::Limit)?; |
| 261 | self.items.push(Planned { |
| 262 | member: Member { |
| 263 | entry: Entry { |
| 264 | entry_id: self.items.len() as u32, |
| 265 | name: name.clone(), |
| 266 | kind: if directory { |
| 267 | EntryKind::Directory |
| 268 | } else { |
| 269 | EntryKind::File |
| 270 | }, |
| 271 | size, |
| 272 | compressed_size: 0, |
| 273 | encrypted: false, |
| 274 | }, |
| 275 | data: Vec::new(), |
| 276 | }, |
| 277 | path: path.clone(), |
| 278 | object: filesystem::object(&input.file)?, |
| 279 | modified: metadata.modified().ok(), |
| 280 | }); |
| 281 | if directory { |
| 282 | let mut children = Vec::new(); |
| 283 | for entry in input.children(&path)? { |
| 284 | check()?; |
| 285 | if self.items.len() + children.len() >= self.limits.entries as usize { |
| 286 | return Err(ErrorCode::Limit); |
| 287 | } |
| 288 | let leaf = entry |
| 289 | .map_err(crate::space::io_error)? |
| 290 | .file_name() |
| 291 | .into_string() |
| 292 | .map_err(|_| ErrorCode::UnsafePath)?; |
| 293 | self.budget.charge(&leaf)?; |
| 294 | children.push(leaf); |
| 295 | } |
| 296 | children.sort(); |
| 297 | for leaf in children { |
| 298 | let child = input.open_child(&path, &leaf)?; |
| 299 | self.visit(path.join(&leaf), format!("{name}/{leaf}"), child, check)?; |
| 300 | } |
| 301 | } |
| 302 | Ok(()) |
| 303 | } |
| 304 | pub fn verify(&self, check: &mut impl FnMut() -> Result<()>) -> Result<()> { |
| 305 | for item in &self.items { |
| 306 | check()?; |
| 307 | item.open()?; |
| 308 | } |
| 309 | Ok(()) |
| 310 | } |
| 311 | } |
| 312 | |
| 313 | #[cfg(test)] |
| 314 | #[path = "../../../tests/rust-archive-worker/create_sources.rs"] |
| 315 | mod tests; |