team-ljyzipelo

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