Debian Codegraph @

src/commands/download.rs

raw
1 use std::collections::BTreeMap;
2 use std::fs::File;
3 use std::io;
4 use std::io::IsTerminal;
5 use std::io::Seek;
6 use std::io::Write;
7 use std::path::Path;
8 use std::path::PathBuf;
9
10 use anyhow::Context;
11
12 use futures_util::StreamExt;
13
14 use tokio::sync::oneshot;
15 use tokio::task::JoinSet;
16 use tokio::task::LocalSet;
17
18 use indicatif::ProgressBar;
19 use indicatif::ProgressStyle;
20 use indicatif::WeakProgressBar;
21
22 use sequoia_net as net;
23 use net::reqwest;
24
25 use tempfile::NamedTempFile;
26
27 use sequoia_openpgp as openpgp;
28 use openpgp::Cert;
29 use openpgp::Fingerprint;
30 use openpgp::KeyHandle;
31 use openpgp::Packet;
32 use openpgp::parse::PacketParser;
33 use openpgp::parse::PacketParserResult;
34 use openpgp::parse::Parse;
35 use openpgp::parse::buffered_reader::{self, BufferedReader};
36 use openpgp::types::KeyFlags;
37
38 use crate::Result;
39 use crate::Sq;
40 use crate::cli::download;
41 use crate::cli::types::TrustAmount;
42 use crate::commands::network::CONNECT_TIMEOUT;
43 use crate::commands::network::USER_AGENT;
44 use crate::commands::verify::verify;
45 use crate::common::key_handle_dealias;
46 use crate::common::pki::authenticate::AuthenticateContext;
47 use crate::common::pki::authenticate::Query;
48 use crate::common::pki::authenticate;
49 use crate::common::ui;
50 use crate::sq::TrustThreshold;
51
52 // So we can deal with either named temp files or files.
53 enum SomeFile {
54 Temp(NamedTempFile),
55 File((File, PathBuf)),
56 }
57
58 impl SomeFile {
59 fn as_ref(&self) -> &File {
60 match self {
61 SomeFile::Temp(t) => t.as_file(),
62 SomeFile::File((f, _)) => &f,
63 }
64 }
65
66 fn as_mut(&mut self) -> &mut File {
67 match self {
68 SomeFile::Temp(t) => t.as_file_mut(),
69 SomeFile::File((ref mut f, _)) => f,
70 }
71 }
72
73 fn path(&self) -> &Path {
74 match self {
75 SomeFile::Temp(t) => t.path(),
76 SomeFile::File((_, p)) => p.as_path(),
77 }
78 }
79
80 /// Writes a copy of the file to `new_path`.
81 ///
82 /// We optimize the case where this file is a temporary file, in
83 /// which case we simply rename it.
84 fn persist<P: AsRef<Path>>(self, new_path: P) -> Result<()> {
85 match self {
86 SomeFile::Temp(t) => {
87 t.persist(new_path)?;
88 },
89
90 SomeFile::File((_, p)) => {
91 // This was sourced from a local file, we cannot
92 // rename that, but we can copy it.
93 std::fs::copy(p, new_path)?;
94 },
95 }
96
97 Ok(())
98 }
99 }
100
101 // Spawn a task to download the `$url` to `$output` using `$http_client`.
102 //
103 // This is a macro rather than a function due to lifetimes.
104 //
105 // `$rt` is uninterpreted, and is returned as is.
106 //
107 // `$limit` causes the download to abort after that many bytes.
108 //
109 // `$file_name` is `$output`'s file name. Its purely used for
110 // decorative purposes.
111 //
112 // `$pb` is a weak reference to a progress bar.
113 macro_rules! get {
114 ($http_client:expr, $rt:expr, $url:expr, $limit:expr, $file_name:expr,
115 $output: expr, $pb:expr) => {{
116 let url: String = $url.into();
117 let http_client: reqwest::Client = $http_client.clone();
118 let limit: Option<usize> = $limit;
119 let file_name: String = $file_name.into();
120 let mut output = $output;
121 let pb: WeakProgressBar = $pb;
122
123 async move {
124 if let Some(local_file_name) = url.strip_prefix("file://") {
125 let local_file_name = PathBuf::from(local_file_name);
126 match File::open(&local_file_name) {
127 Ok(file) => {
128 Ok(($rt, SomeFile::File((file, local_file_name))))
129 }
130 Err(err) => Err(err.into()),
131 }
132 } else {
133 let mut bytes = 0;
134 let response = http_client.get(&url).send()
135 .await
136 .and_then(|r| r.error_for_status())
137 .with_context(|| format!("Fetching {}", url))?;
138
139 let len = response.content_length();
140 if let Some(pb) = pb.upgrade() {
141 if let Some(len) = len {
142 pb.inc_length(len);
143 } else {
144 // We don't know how much we need to download. Switch
145 // to a spinner.
146 if ! pb.is_hidden() {
147 pb.set_style(ProgressStyle::default_spinner());
148 }
149 }
150 }
151
152 let mut stream = response.bytes_stream();
153 while let Some(item) = stream.next().await {
154 let item = item.with_context(|| {
155 format!("Fetching {}", url)
156 })?;
157 output.write_all(item.as_ref()).with_context(|| {
158 format!("Writing to {}", file_name)
159 })?;
160 bytes += item.len();
161 pb.upgrade().map(|pb| pb.inc(item.len() as u64));
162
163 if let Some(limit) = limit {
164 if bytes > limit {
165 return Err(anyhow::anyhow!(
166 "{} exceeded download limit size ({} bytes)",
167 url, limit));
168 }
169 }
170 }
171
172 output.flush()?;
173
174 Ok::<_, anyhow::Error>(($rt, SomeFile::Temp(output)))
175 }
176 }
177 }}
178 }
179
180 pub fn dispatch(sq: Sq, c: download::Command)
181 -> Result<()>
182 {
183 let url = c.url;
184 let signature_url = c.detached;
185 let signatures = c.signatures;
186 let signers =
187 sq.resolve_certs_or_fail(&c.signers, TrustThreshold::Full)?;
188 let output = c.output;
189
190 if ! sq.quiet() && ! sq.batch {
191 let output_is_terminal
192 = output.path().is_none() && std::io::stdout().is_terminal();
193 if output_is_terminal {
194 weprintln!("Warning: will write the data to stdout, \
195 which appears to be a terminal. Use --output \
196 to write to a file instead.");
197 }
198 }
199
200
201 // Create the output file early. Otherwise we may download a lot
202 // of data and then fail to copy it.
203 let mut output_file_;
204 let mut stdout_;
205 let mut output_file: &mut dyn Write = if let Some(file) = output.path() {
206 output_file_ = if sq.overwrite {
207 File::create(file)
208 .with_context(|| format!("Opening {}", file.display()))?
209 } else {
210 File::options().write(true).create_new(true).open(file)
211 .map_err(|err| {
212 if err.kind() == std::io::ErrorKind::AlreadyExists {
213 return anyhow::anyhow!(
214 "File {} exists, use \"sq --overwrite ...\" to overwrite",
215 file.display(),
216 );
217 }
218 err.into()
219 })
220 .with_context(|| format!("Opening {}", file.display()))?
221 };
222 &mut output_file_
223 } else {
224 stdout_ = std::io::stdout();
225 &mut stdout_
226 };
227
228
229 // Create the progress bar.
230 let progress_bar = if sq.verbose() || sq.batch {
231 ProgressBar::hidden()
232 } else {
233 ProgressBar::new(0)
234 .with_style(ProgressStyle::with_template(
235 "{wide_bar} {decimal_bytes}/{decimal_total_bytes} ({eta} left)")
236 .expect("valid format"))
237 };
238
239 // A temporary file for the main data. If output is not stdout,
240 // we try and put it in the same directory as where it should end
241 // up.
242 let data_file = {
243 let mut data_file = tempfile::Builder::new();
244 data_file.prefix("sq-download");
245
246 let partial;
247 if let Some(path) = output.path() {
248 if let Some(file_name) = path.file_name() {
249 partial = format!(
250 "{}-partial",
251 String::from_utf8_lossy(file_name.as_encoded_bytes()));
252 data_file.prefix(&partial);
253 }
254
255 if let Some(directory) = path.parent() {
256 data_file.tempfile_in(directory)
257 } else {
258 let cwd = std::env::current_dir()?;
259 data_file.tempfile_in(cwd)
260 }
261 } else {
262 data_file.tempfile()
263 }.context("Creating temporary file")?
264 };
265
266 let http_client = reqwest::Client::builder()
267 .user_agent(USER_AGENT)
268 .connect_timeout(CONNECT_TIMEOUT)
269 .build()?;
270
271 let requests = LocalSet::new();
272 let mut task_set = JoinSet::new();
273
274 // Since JoinSet::join_next has to return the same type, we use
275 // the following to discriminate the tasks.
276 enum Task {
277 Url,
278 Signature,
279 }
280
281 // Schedule the download of the file.
282 task_set.spawn_local_on(
283 get!(http_client.clone(), Task::Url, url, None,
284 data_file.path().display().to_string(), data_file,
285 progress_bar.downgrade()),
286 &requests);
287
288 // We need to do some acrobatics!!! After we download the
289 // signature file, we want to make sure that we can authenticate a
290 // signer. This means we need to use sq. But, we can't move sq
291 // to an async task, because sq has a lifetime that is shorter
292 // than 'static. Instead, we set up a scoped thread, which can
293 // use variables with lifetimes less than static, and then do the
294 // processing there.
295 let signature_url_ = signature_url.clone();
296 let (mut data_file, signature_file) = std::thread::scope(|scope| {
297 // Schedule the download of the signature.
298 if let Some(ref url) = signature_url_ {
299 let sig_file = tempfile::NamedTempFile::new()?;
300
301 let getter = get!(
302 http_client.clone(), Task::Signature, url, None,
303 sig_file.path().display().to_string(), sig_file,
304 progress_bar.downgrade());
305
306 let (request_tx, request_rx) = oneshot::channel();
307 let (response_tx, response_rx) = oneshot::channel();
308
309 task_set.spawn_local_on(
310 async move {
311 let (task, sig_file) = getter.await?;
312
313 // The processing is handled by the thread below.
314 if request_tx.send(sig_file).is_err() {
315 return Err(anyhow::anyhow!(
316 "internal error: protocol violation"));
317 }
318 let sig_file = response_rx.await??;
319 Ok((task, sig_file))
320 },
321 &requests);
322
323 let progress_bar_ = progress_bar.downgrade();
324 let sq_ = &sq;
325 let signers_ = &signers;
326 scope.spawn(move || {
327 let result = (|| {
328 let progress_bar = progress_bar_;
329 let sq = sq_;
330 let signers = signers_;
331
332 let mut sig_file = if let Ok(sig_file)
333 = request_rx.blocking_recv()
334 {
335 sig_file
336 } else {
337 return Err(anyhow::anyhow!(
338 "internal error: protocol violation"));
339 };
340
341 // Read the signature data and make sure we can
342 // authenticate at least one issuer's certificate.
343 sig_file.as_mut().rewind()?;
344 let mut ppr = PacketParser::from_reader(sig_file.as_ref())
345 .context("Parsing detached signature: either the signature \
346 file does not actually contain an OpenPGP \
347 signature, or it is corrupted.")?;
348 let mut signatures = Vec::new();
349 while let PacketParserResult::Some(pp) = ppr {
350 let (packet, next_ppr) = pp.next()?;
351 ppr = next_ppr;
352
353 match packet {
354 Packet::Signature(sig) => {
355 signatures.push(sig);
356 }
357 Packet::Marker(_) => (),
358 _ => {
359 return Err(anyhow::anyhow!(
360 "Signature file does not contain a detached \
361 signature. It includes a {}.",
362 packet.tag()));
363 }
364 }
365 }
366
367 if signatures.is_empty() {
368 return Err(anyhow::anyhow!(
369 "Signature file does not contain any signatures."));
370 }
371
372 let mut seen: BTreeMap<Fingerprint, Cert> = BTreeMap::new();
373 let mut authenticated = false;
374 for sig in signatures.iter() {
375 for issuer in sig.get_issuers() {
376 if let Some(cert)
377 = signers.iter().find(|c| c.key_handle().aliases(&issuer))
378 {
379 if seen.contains_key(&cert.fingerprint()) {
380 // Already saw that certificate.
381 continue;
382 }
383
384 authenticated = true;
385
386 if let Some(pb) = progress_bar.upgrade() {
387 pb.suspend(|| {
388 weprintln!(
389 "Alleged signer {} is good listed.",
390 cert.fingerprint());
391 })
392 }
393 } else if let Ok(cert)
394 = sq.lookup_one(issuer,
395 Some(KeyFlags::signing()),
396 false)
397 {
398 if seen.contains_key(&cert.fingerprint()) {
399 // Already saw that certificate.
400 continue;
401 }
402
403 let mut auth = || {
404 let result = authenticate(
405 &mut std::io::stderr(),
406 &sq,
407 AuthenticateContext::Download,
408 vec![
409 Query::for_key_handle(
410 None, cert.key_handle())
411 ],
412 false, // gossip
413 false, // show unusable
414 false, // certification network
415 Some(TrustAmount::Full), // trust amount
416 true, // show paths
417 );
418
419 if let Err(err) = result {
420 weprintln!("Can't authenticate the \
421 alleged signer:");
422 let _ = ui::emit_cert(
423 &mut io::stderr(),
424 sq, &cert);
425
426 weprintln!(
427 initial_indent = " - ",
428 "{}",
429 crate::one_line_error_chain(err));
430 weprintln!();
431 } else {
432 authenticated = true;
433 }
434 };
435
436 if let Some(pb) = progress_bar.upgrade() {
437 pb.suspend(auth);
438 } else {
439 auth();
440 }
441
442 seen.insert(cert.fingerprint(),
443 cert);
444 }
445 }
446 }
447
448 if ! authenticated {
449 if let Some(pb) = progress_bar.upgrade() {
450 pb.finish_and_clear();
451 }
452
453 if seen.is_empty() {
454 weprintln!("We can't verify the signature, because \
455 we don't have certificates for any of \
456 the alleged signers:");
457 } else {
458 weprintln!("We can't verify the signature, because \
459 we can't authenticate any of the \
460 alleged signers:");
461 }
462
463 weprintln!();
464 let issuers = signatures.iter()
465 .flat_map(|sig| sig.get_issuers().into_iter())
466 .collect::<Vec<_>>();
467 let issuers
468 = key_handle_dealias(&issuers).collect::<Vec<_>>();
469
470 if issuers.is_empty() {
471 weprintln!(initial_indent = " - ",
472 "No issuers (the signature may be \
473 malformed)");
474 } else {
475 let mut missing = Vec::new();
476 for issuer in issuers.iter() {
477 if let KeyHandle::Fingerprint(fpr) = issuer {
478 if let Some(cert) = seen.get(fpr) {
479 weprintln!(initial_indent = " - ",
480 "{} {}",
481 issuer,
482 sq.best_userid(cert, true)
483 .display());
484 } else {
485 weprintln!(initial_indent = " - ",
486 "{} (missing certificate)",
487 issuer);
488 missing.push(issuer);
489 }
490 } else {
491 weprintln!(initial_indent = " - ",
492 "{} (missing certificate)",
493 issuer);
494 missing.push(issuer);
495 }
496 }
497
498 if ! missing.is_empty() {
499 let mut hint = sq.hint(format_args!(
500 "Try searching public directories:"))
501 .sq().arg("network").arg("search");
502 for issuer in issuers.into_iter() {
503 hint = hint.arg(issuer.to_string());
504 }
505 hint.done();
506 }
507 if let Some(issuer) = seen.keys().next() {
508 sq.hint(format_args!(
509 "Verify that one of the certificates is \
510 authentic, and then link it:"))
511 .sq().arg("pki").arg("link").arg("add")
512 .arg_value_hidden("--cert",
513 issuer,
514 "FINGERPRINT")
515 .done();
516 }
517 }
518
519 return Err(anyhow::anyhow!("\
520 Can't authenticate any of the alleged signers"));
521 }
522
523 drop(ppr);
524
525 Ok(sig_file)
526 })();
527
528 if let Err(result) = response_tx.send(result) {
529 // (send returns result on failure.) We failed to
530 // return the result. Don't make things worse by
531 // swallowing any error.
532 if let Err(err) = result.as_ref() {
533 crate::print_error_chain(&err);
534 }
535
536 Err(anyhow::anyhow!("Internal error: failed to return \
537 result to caller"))
538 } else {
539 Ok(())
540 }
541 });
542 }
543
544 // And GO!!!
545 let rt = tokio::runtime::Runtime::new()?;
546 let (data_file, signature_file) = requests.block_on(&rt, async move {
547 let mut data_file = None;
548 let mut signature_file = None;
549
550 while let Some(result) = task_set.join_next().await {
551 match result {
552 Ok(Ok((Task::Signature, file))) => signature_file = Some(file),
553 Ok(Ok((Task::Url, file))) => data_file = Some(file),
554 Ok(Err(err)) => {
555 if data_file.is_none() {
556 eprintln!();
557 eprintln!("Aborting download.");
558 }
559 return Err(err);
560 }
561 Err(err) => {
562 return Err(err).context("While downloading data");
563 }
564 }
565 }
566
567 let data_file = if let Some(data_file) = data_file {
568 data_file
569 } else {
570 return Err(anyhow::anyhow!(
571 "Internal error while downloading data file"));
572 };
573
574 if signature_url_.is_some() && signature_file.is_none() {
575 return Err(anyhow::anyhow!(
576 "Internal error while downloading signature file"));
577 }
578
579 Ok::<_, anyhow::Error>((data_file, signature_file))
580 })?;
581
582 Ok::<_, anyhow::Error>((data_file, signature_file))
583 })?;
584
585 drop(progress_bar);
586
587 weprintln!();
588 weprintln!("Finished downloading data. Authenticating data.");
589 weprintln!();
590
591 data_file.as_mut().rewind()?;
592
593 let result = verify(
594 sq,
595 buffered_reader::File::new_with_cookie(
596 data_file.as_ref().try_clone()?, data_file.path(),
597 Default::default())?.into_boxed(),
598 signature_file.as_ref().map(|f| f.path().to_path_buf()),
599 "--signature-url",
600 signature_url.map(PathBuf::from),
601 &mut output_file,
602 signatures,
603 signers);
604
605 if let Err(err) = result {
606 if let Some(path) = output.path() {
607 if let Err(err) = std::fs::remove_file(path) {
608 weprintln!("Verification failed, failed to remove \
609 unverified output saved to {}: {}",
610 path.display(), err);
611 }
612 }
613
614 return Err(err);
615 }
616
617 if signature_file.is_some() {
618 // Verify doesn't copy the data when checking detached
619 // signatures. Do it now.
620 if let Some(p) = output.path() {
621 data_file.persist(p)?;
622 } else {
623 // Copy the data to stdout.
624 data_file.as_mut().rewind()?;
625 std::io::copy(&mut data_file.as_ref(), output_file)?;
626 }
627 }
628
629 result
630 }