team-ljyzipelo

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