team-ljyzipelo

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