| 1 | use crate::{ |
| 2 | archive::{self, Member}, |
| 3 | filesystem::{self, Dir}, |
| 4 | protocol::*, |
| 5 | wire::{Reader, Writer}, |
| 6 | }; |
| 7 | use std::{ |
| 8 | collections::BTreeSet, |
| 9 | io::{Read, Write}, |
| 10 | sync::{Arc, Mutex}, |
| 11 | time::{Duration, Instant}, |
| 12 | }; |
| 13 | |
| 14 | type Result<T> = std::result::Result<T, ErrorCode>; |
| 15 | struct State<W> { |
| 16 | writer: Writer<W>, |
| 17 | cancelled: bool, |
| 18 | phase: u8, |
| 19 | fault: Option<ErrorCode>, |
| 20 | } |
| 21 | struct Job<W> { |
| 22 | state: Arc<Mutex<State<W>>>, |
| 23 | started: Instant, |
| 24 | terminal: Terminal, |
| 25 | } |
| 26 | impl<W: Write> Job<W> { |
| 27 | fn event(&mut self, event: Message) -> Result<()> { |
| 28 | let mut state = self.state.lock().map_err(|_| ErrorCode::Internal)?; |
| 29 | state.writer.send(&event).map_err(|_| { |
| 30 | state.fault = Some(ErrorCode::Io); |
| 31 | ErrorCode::Io |
| 32 | }) |
| 33 | } |
| 34 | fn check(&mut self) -> Result<()> { |
| 35 | if self.started.elapsed() > Duration::from_secs(300) { |
| 36 | return Err(ErrorCode::Limit); |
| 37 | } |
| 38 | let state = self.state.lock().map_err(|_| ErrorCode::Internal)?; |
| 39 | if let Some(error) = state.fault { |
| 40 | return Err(error); |
| 41 | } |
| 42 | if state.cancelled && state.phase == 0 { |
| 43 | return Err(ErrorCode::None); |
| 44 | } |
| 45 | Ok(()) |
| 46 | } |
| 47 | fn cutoff(&mut self) -> Result<()> { |
| 48 | self.check()?; |
| 49 | let mut state = self.state.lock().map_err(|_| ErrorCode::Internal)?; |
| 50 | if state.phase == 0 && state.cancelled { |
| 51 | return Err(ErrorCode::None); |
| 52 | } |
| 53 | state.phase = 1; |
| 54 | Ok(()) |
| 55 | } |
| 56 | fn progress( |
| 57 | &mut self, |
| 58 | stage: Stage, |
| 59 | bytes: u64, |
| 60 | total: Option<u64>, |
| 61 | entries: u32, |
| 62 | ) -> Result<()> { |
| 63 | self.event(Message::Progress { |
| 64 | stage, |
| 65 | processed_bytes: bytes, |
| 66 | total_bytes: total, |
| 67 | completed_entries: entries, |
| 68 | }) |
| 69 | } |
| 70 | fn output( |
| 71 | &mut self, |
| 72 | root: &Dir, |
| 73 | name: &str, |
| 74 | data: &[u8], |
| 75 | id: Option<u32>, |
| 76 | last: bool, |
| 77 | ) -> Result<()> { |
| 78 | self.check()?; |
| 79 | self.progress( |
| 80 | Stage::Write, |
| 81 | 0, |
| 82 | Some(data.len() as u64), |
| 83 | self.terminal.created_count as u32, |
| 84 | )?; |
| 85 | let p = filesystem::publish(root, name, data, &mut |commit| { |
| 86 | if commit && last { |
| 87 | self.cutoff() |
| 88 | } else { |
| 89 | self.check() |
| 90 | } |
| 91 | }); |
| 92 | self.terminal.retained_partial_count += p.retained; |
| 93 | if p.cleanup != Cleanup::Complete { |
| 94 | self.terminal.cleanup = p.cleanup; |
| 95 | } |
| 96 | if p.created { |
| 97 | self.terminal.created_count += 1; |
| 98 | self.terminal.publication = Publication::Partial; |
| 99 | self.terminal.durability = match (self.terminal.durability, p.durability) { |
| 100 | (Durability::Failed, _) | (_, Durability::Failed) => Durability::Failed, |
| 101 | (Durability::Unconfirmed, _) | (_, Durability::Unconfirmed) => { |
| 102 | Durability::Unconfirmed |
| 103 | } |
| 104 | _ => p.durability, |
| 105 | }; |
| 106 | self.event(Message::Output { |
| 107 | entry_id: id, |
| 108 | relative_name: name.to_owned(), |
| 109 | disposition: Disposition::Created, |
| 110 | })?; |
| 111 | } |
| 112 | if p.uncertain { |
| 113 | self.terminal.publication = Publication::Uncertain; |
| 114 | self.terminal.durability = Durability::Unconfirmed; |
| 115 | self.event(Message::Output { |
| 116 | entry_id: id, |
| 117 | relative_name: name.to_owned(), |
| 118 | disposition: Disposition::CommitUncertain, |
| 119 | })?; |
| 120 | } |
| 121 | if p.retained != 0 { |
| 122 | self.event(Message::Output { |
| 123 | entry_id: id, |
| 124 | relative_name: p.retained_name.clone().ok_or(ErrorCode::Internal)?, |
| 125 | disposition: Disposition::PartialRetained, |
| 126 | })?; |
| 127 | } |
| 128 | if let Some(error) = p.error { |
| 129 | return Err(error); |
| 130 | } |
| 131 | Ok(()) |
| 132 | } |
| 133 | fn run(&mut self, start: Start) -> Result<()> { |
| 134 | if !start.limits.valid() { |
| 135 | return Err(ErrorCode::InvalidRequest); |
| 136 | } |
| 137 | self.event(Message::Accepted { |
| 138 | action: start.action.kind(), |
| 139 | encryption: false, |
| 140 | })?; |
| 141 | self.check()?; |
| 142 | match start.action { |
| 143 | Action::List { |
| 144 | archive: ref source, |
| 145 | } |
| 146 | | Action::Extract { |
| 147 | archive: ref source, |
| 148 | .. |
| 149 | } => { |
| 150 | let extract = matches!(start.action, Action::Extract { .. }); |
| 151 | let path = source.to_path()?; |
| 152 | self.progress(Stage::Read, 0, None, 0)?; |
| 153 | let snapshot = |
| 154 | filesystem::snapshot(&path, start.limits.input, &mut || self.check())?; |
| 155 | if let Action::Extract { |
| 156 | list_id: Some(expected), |
| 157 | .. |
| 158 | } = &start.action |
| 159 | { |
| 160 | if expected.catalog_version != 1 |
| 161 | || expected.source_object != snapshot.object |
| 162 | || expected.archive_bytes != snapshot.bytes.len() as u64 |
| 163 | || expected.archive_sha256 != snapshot.hash |
| 164 | { |
| 165 | return Err(ErrorCode::SourceChanged); |
| 166 | } |
| 167 | } |
| 168 | self.progress( |
| 169 | Stage::Decode, |
| 170 | snapshot.bytes.len() as u64, |
| 171 | Some(snapshot.bytes.len() as u64), |
| 172 | 0, |
| 173 | )?; |
| 174 | let mut catalog = |
| 175 | archive::parse(&snapshot.bytes, start.limits, extract, &mut || self.check())?; |
| 176 | let list_id = ListId { |
| 177 | catalog_version: 1, |
| 178 | format: catalog.format, |
| 179 | source_object: snapshot.object, |
| 180 | archive_bytes: snapshot.bytes.len() as u64, |
| 181 | archive_sha256: snapshot.hash, |
| 182 | }; |
| 183 | if !extract { |
| 184 | for member in &catalog.members { |
| 185 | self.check()?; |
| 186 | self.event(Message::Entry(member.entry.clone()))?; |
| 187 | } |
| 188 | self.event(Message::ListEnd { |
| 189 | entry_count: catalog.members.len() as u32, |
| 190 | list_id, |
| 191 | })?; |
| 192 | } else if let Action::Extract { |
| 193 | destination, |
| 194 | selection, |
| 195 | list_id: expected, |
| 196 | gzip_output_name, |
| 197 | .. |
| 198 | } = start.action |
| 199 | { |
| 200 | if expected |
| 201 | .as_ref() |
| 202 | .is_some_and(|expected| *expected != list_id) |
| 203 | { |
| 204 | return Err(ErrorCode::SourceChanged); |
| 205 | } |
| 206 | let selected = match selection { |
| 207 | Selection::All => None, |
| 208 | Selection::EntryIds(ids) => { |
| 209 | let n = ids.len(); |
| 210 | let set = ids.into_iter().collect::<BTreeSet<_>>(); |
| 211 | if expected.is_none() |
| 212 | || set.is_empty() |
| 213 | || n != set.len() |
| 214 | || set.iter().any(|id| *id as usize >= catalog.members.len()) |
| 215 | { |
| 216 | return Err(ErrorCode::InvalidRequest); |
| 217 | } |
| 218 | Some(set) |
| 219 | } |
| 220 | }; |
| 221 | if catalog.members.iter().any(|m| m.entry.encrypted) { |
| 222 | return Err(ErrorCode::UnsupportedFeature); |
| 223 | } |
| 224 | if catalog |
| 225 | .members |
| 226 | .iter() |
| 227 | .any(|m| !matches!(m.entry.kind, EntryKind::File | EntryKind::Directory)) |
| 228 | { |
| 229 | return Err(ErrorCode::UnsafePath); |
| 230 | } |
| 231 | if catalog.format == Format::Gzip { |
| 232 | let name = gzip_output_name.ok_or(ErrorCode::InvalidRequest)?; |
| 233 | let checked = archive::valid_name(&name, false) |
| 234 | .map_err(|_| ErrorCode::InvalidRequest)?; |
| 235 | if checked.contains('/') { |
| 236 | return Err(ErrorCode::InvalidRequest); |
| 237 | } |
| 238 | catalog.members[0].entry.name = checked; |
| 239 | } else if gzip_output_name.is_some() { |
| 240 | return Err(ErrorCode::InvalidRequest); |
| 241 | } |
| 242 | let root = Dir::root(&destination.to_path()?)?; |
| 243 | let members = catalog |
| 244 | .members |
| 245 | .into_iter() |
| 246 | .filter(|m| { |
| 247 | selected |
| 248 | .as_ref() |
| 249 | .is_none_or(|s| s.contains(&m.entry.entry_id)) |
| 250 | }) |
| 251 | .collect::<Vec<_>>(); |
| 252 | let dirs = archive::output_directories(&members)?; |
| 253 | let files = members |
| 254 | .iter() |
| 255 | .filter(|m| m.entry.kind == EntryKind::File) |
| 256 | .collect::<Vec<_>>(); |
| 257 | let mut names = dirs |
| 258 | .iter() |
| 259 | .map(|n| (n.clone(), EntryKind::Directory)) |
| 260 | .collect::<Vec<_>>(); |
| 261 | names.extend( |
| 262 | files |
| 263 | .iter() |
| 264 | .map(|m| (m.entry.name.clone(), EntryKind::File)), |
| 265 | ); |
| 266 | filesystem::preflight(&root, &names)?; |
| 267 | for name in dirs { |
| 268 | self.check()?; |
| 269 | let (created, durability) = filesystem::directory(&root, &name)?; |
| 270 | if created { |
| 271 | self.terminal.created_count += 1; |
| 272 | self.terminal.publication = Publication::Partial; |
| 273 | self.terminal.durability = durability; |
| 274 | self.event(Message::Output { |
| 275 | entry_id: None, |
| 276 | relative_name: name, |
| 277 | disposition: Disposition::Created, |
| 278 | })?; |
| 279 | if durability == Durability::Failed { |
| 280 | return Err(ErrorCode::Io); |
| 281 | } |
| 282 | } |
| 283 | } |
| 284 | for (index, m) in files.iter().enumerate() { |
| 285 | self.output( |
| 286 | &root, |
| 287 | &m.entry.name, |
| 288 | &m.data, |
| 289 | Some(m.entry.entry_id), |
| 290 | index + 1 == files.len(), |
| 291 | )?; |
| 292 | } |
| 293 | self.terminal.publication = Publication::Complete; |
| 294 | } |
| 295 | } |
| 296 | Action::CreateZip { |
| 297 | sources, |
| 298 | output_file, |
| 299 | method, |
| 300 | encryption, |
| 301 | } => { |
| 302 | if encryption != Encryption::None { |
| 303 | return Err(ErrorCode::UnsupportedFeature); |
| 304 | } |
| 305 | if sources.len() > start.limits.entries as usize { |
| 306 | return Err(ErrorCode::Limit); |
| 307 | } |
| 308 | let mut members = Vec::new(); |
| 309 | let mut consumed = 0; |
| 310 | for source in sources { |
| 311 | self.check()?; |
| 312 | let name = archive::valid_name(&source.archive_name, false)?; |
| 313 | let snapshot = filesystem::snapshot( |
| 314 | &source.path.to_path()?, |
| 315 | start.limits.input - consumed, |
| 316 | &mut || self.check(), |
| 317 | )?; |
| 318 | consumed += snapshot.bytes.len() as u64; |
| 319 | members.push(Member { |
| 320 | entry: Entry { |
| 321 | entry_id: members.len() as u32, |
| 322 | name, |
| 323 | kind: EntryKind::File, |
| 324 | size: snapshot.bytes.len() as u64, |
| 325 | compressed_size: 0, |
| 326 | encrypted: false, |
| 327 | }, |
| 328 | data: snapshot.bytes, |
| 329 | }); |
| 330 | } |
| 331 | let bytes = |
| 332 | archive::create_zip(&members, method, start.limits, &mut || self.check())?; |
| 333 | let output = output_file.to_path()?; |
| 334 | let leaf = output |
| 335 | .file_name() |
| 336 | .and_then(|n| n.to_str()) |
| 337 | .ok_or(ErrorCode::InvalidRequest)?; |
| 338 | let name = archive::valid_name(leaf, false)?; |
| 339 | let root = Dir::root(output.parent().ok_or(ErrorCode::InvalidRequest)?)?; |
| 340 | filesystem::preflight(&root, &[(name.clone(), EntryKind::File)])?; |
| 341 | self.output(&root, &name, &bytes, None, true)?; |
| 342 | self.terminal.publication = Publication::Complete; |
| 343 | } |
| 344 | } |
| 345 | self.cutoff()?; |
| 346 | Ok(()) |
| 347 | } |
| 348 | } |
| 349 | pub fn serve<R: Read + Send + 'static, W: Write + Send + 'static>( |
| 350 | input: R, |
| 351 | output: W, |
| 352 | ) -> std::io::Result<()> { |
| 353 | let mut reader = Reader::new(input); |
| 354 | let (job, _, message) = reader |
| 355 | .read()? |
| 356 | .ok_or_else(|| std::io::Error::from(std::io::ErrorKind::UnexpectedEof))?; |
| 357 | let Message::Start(start) = message else { |
| 358 | return Err(std::io::Error::new( |
| 359 | std::io::ErrorKind::InvalidData, |
| 360 | "Start required", |
| 361 | )); |
| 362 | }; |
| 363 | let state = Arc::new(Mutex::new(State { |
| 364 | writer: Writer::new(output, job), |
| 365 | cancelled: false, |
| 366 | phase: 0, |
| 367 | fault: None, |
| 368 | })); |
| 369 | let control = Arc::clone(&state); |
| 370 | std::thread::spawn(move || { |
| 371 | loop { |
| 372 | let command = reader.read(); |
| 373 | let Ok(Some((_, sequence, message))) = command else { |
| 374 | if command.is_err() { |
| 375 | if let Ok(mut state) = control.lock() { |
| 376 | if state.phase < 2 { |
| 377 | state.fault = Some(ErrorCode::Protocol); |
| 378 | } |
| 379 | } |
| 380 | } |
| 381 | break; |
| 382 | }; |
| 383 | let Ok(mut state) = control.lock() else { |
| 384 | break; |
| 385 | }; |
| 386 | if state.phase == 3 { |
| 387 | break; |
| 388 | } |
| 389 | match message { |
| 390 | Message::Cancel => { |
| 391 | let status = match state.phase { |
| 392 | 2 => CancelStatus::Finished, |
| 393 | 1 => CancelStatus::TooLate, |
| 394 | _ if state.cancelled => CancelStatus::AlreadyRequested, |
| 395 | _ => { |
| 396 | state.cancelled = true; |
| 397 | CancelStatus::Requested |
| 398 | } |
| 399 | }; |
| 400 | if state |
| 401 | .writer |
| 402 | .send(&Message::CancelAck { |
| 403 | request_sequence: sequence, |
| 404 | status, |
| 405 | }) |
| 406 | .is_err() |
| 407 | { |
| 408 | state.fault = Some(ErrorCode::Io); |
| 409 | break; |
| 410 | } |
| 411 | } |
| 412 | _ => { |
| 413 | state.fault = Some(ErrorCode::Protocol); |
| 414 | break; |
| 415 | } |
| 416 | } |
| 417 | } |
| 418 | }); |
| 419 | let mut context = Job { |
| 420 | state: Arc::clone(&state), |
| 421 | started: Instant::now(), |
| 422 | terminal: Terminal { |
| 423 | outcome: Outcome::Completed, |
| 424 | error: ErrorCode::None, |
| 425 | publication: Publication::None, |
| 426 | created_count: 0, |
| 427 | retained_partial_count: 0, |
| 428 | durability: Durability::NotApplicable, |
| 429 | cleanup: Cleanup::Complete, |
| 430 | detail: String::new(), |
| 431 | }, |
| 432 | }; |
| 433 | let result = std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| context.run(start))); |
| 434 | let error = match result { |
| 435 | Ok(r) => r.err(), |
| 436 | Err(_) => { |
| 437 | context.terminal.publication = Publication::Uncertain; |
| 438 | context.terminal.cleanup = Cleanup::Unconfirmed; |
| 439 | Some(ErrorCode::Internal) |
| 440 | } |
| 441 | }; |
| 442 | let mut state = state |
| 443 | .lock() |
| 444 | .map_err(|_| std::io::Error::other("worker state poisoned"))?; |
| 445 | state.phase = 2; |
| 446 | if let Some(error) = state.fault.or(error) { |
| 447 | context.terminal.error = error; |
| 448 | context.terminal.outcome = if error == ErrorCode::None { |
| 449 | Outcome::Cancelled |
| 450 | } else { |
| 451 | Outcome::Failed |
| 452 | }; |
| 453 | context.terminal.detail = match error { |
| 454 | ErrorCode::None => "취소됨", |
| 455 | ErrorCode::UnsupportedFeature => "암호 또는 해당 기능 미지원", |
| 456 | ErrorCode::SourceChanged => "파일이 변경됨. 다시 열어 목록을 확인해야 함", |
| 457 | _ => "작업 실패. 오류 코드와 게시 상태를 확인해야 함", |
| 458 | } |
| 459 | .to_owned(); |
| 460 | } |
| 461 | state.writer.send(&Message::Terminal(context.terminal))?; |
| 462 | state.phase = 3; |
| 463 | Ok(()) |
| 464 | } |