team-ljyzipelo

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