Debian Codegraph @

src/commands/network.rs

raw
1 //! Network services.
2
3 use std::collections::{BTreeMap, BTreeSet, HashSet};
4 use std::fmt;
5 use std::fs::{self, DirEntry};
6 use std::path::{Path, PathBuf};
7 use std::sync::Arc;
8 use std::time::Duration;
9
10 use anyhow::Context;
11 use clap::ArgMatches;
12 use indicatif::ProgressBar;
13 use tokio::task::JoinSet;
14
15 use sequoia_openpgp as openpgp;
16 use openpgp::{
17 Fingerprint,
18 Result,
19 KeyHandle,
20 armor,
21 cert::{
22 Cert,
23 CertParser,
24 },
25 crypto::Signer,
26 Packet,
27 packet::{
28 signature::SignatureBuilder,
29 UserID,
30 },
31 parse::Parse,
32 serialize::Serialize,
33 types::{
34 KeyFlags,
35 RevocationStatus,
36 SignatureType,
37 },
38 };
39 use sequoia_net as net;
40 use net::{
41 KeyServer,
42 wkd,
43 dane,
44 reqwest::{StatusCode, Url},
45 };
46
47 use sequoia_cert_store as cert_store;
48 use cert_store::LazyCert;
49 use cert_store::Store;
50 use cert_store::StoreUpdate;
51 use cert_store::store::UserIDQueryParams;
52
53 use crate::{
54 Convert,
55 commands::{
56 FileOrStdout,
57 active_certification,
58 },
59 common::ui,
60 output::{
61 import::ImportStats,
62 pluralize::Pluralize,
63 },
64 Sq,
65 print_error_chain,
66 utils::cert_exportable,
67 };
68
69 use crate::cli;
70 use crate::sq::TrustThreshold;
71
72 /// User agent for http communications.
73 pub const USER_AGENT: &'static str = concat!("sq/", env!("CARGO_PKG_VERSION"));
74
75 /// How long to wait for the initial http connection.
76 pub const CONNECT_TIMEOUT: Duration = Duration::new(5, 0);
77
78 /// How long to wait for each individual http request.
79 pub const REQUEST_TIMEOUT: Duration = Duration::new(5, 0);
80
81 pub fn dispatch(sq: Sq, c: cli::network::Command, matches: &ArgMatches)
82 -> Result<()>
83 {
84 let matches = matches.subcommand().unwrap().1;
85 use cli::network::Subcommands;
86 match c.subcommand {
87 Subcommands::Search(mut command) => {
88 command.iterations_source = matches.value_source("iterations");
89 command.servers_source = matches.value_source("servers");
90 command.use_wkd_source = matches.value_source("use_wkd");
91 command.use_dane_source = matches.value_source("use_dane");
92 dispatch_search(sq, command)
93 },
94
95 Subcommands::Keyserver(command) =>
96 dispatch_keyserver(sq, command, matches),
97
98 Subcommands::Wkd(command) =>
99 dispatch_wkd(sq, command),
100
101 Subcommands::Dane(command) =>
102 dispatch_dane(sq, command),
103 }
104 }
105
106
107 /// Import the certificates into the local certificate store.
108 ///
109 /// This does not certify the certificates.
110 pub fn import_certs(sq: &Sq, certs: Vec<Cert>) -> Result<()> {
111 if certs.is_empty() {
112 // No need to do and say anything.
113 return Ok(());
114 }
115
116 let cert_store = sq.cert_store_or_else()
117 .context("Inserting results")?;
118
119 let mut stats = ImportStats::default();
120
121 let o = &mut std::io::stderr();
122
123 for cert in certs.iter() {
124 cert_store.update_by(Arc::new(cert.clone().into()), &mut stats)
125 .with_context(|| {
126 let sanitized_userid = sq.best_userid(&cert, true);
127
128 format!("Inserting {}, {}",
129 cert.fingerprint(), sanitized_userid.display())
130 })?;
131 }
132
133 stats.print_summary(o, sq)?;
134
135 for vcert in certs.iter()
136 .filter_map(|cert| cert.with_policy(sq.policy, sq.time).ok())
137 .filter(|vcert| vcert.alive().is_ok())
138 {
139 let mut hint = sq.hint(format_args!(
140 "After checking that the certificate {} really belongs to the \
141 stated owner, you can mark the certificate as authenticated. \
142 Each stated user ID can be marked individually using:",
143 vcert.fingerprint()));
144
145 let mut count = 0;
146 for uid in vcert.userids()
147 .filter_map(|uid| std::str::from_utf8(uid.userid().value())
148 .map(ToString::to_string).ok())
149 {
150 hint = hint
151 .sq().arg("pki").arg("link").arg("add")
152 .arg_value("--cert", vcert.fingerprint())
153 .arg_value("--userid", uid)
154 .done();
155
156 count += 1;
157 }
158
159 if count > 1 {
160 hint.hint(format_args!(
161 "Alternatively, all user IDs can be marked as authenticated \
162 using:"))
163 .sq().arg("pki").arg("link").arg("add")
164 .arg_value("--cert", vcert.fingerprint())
165 .arg("--all")
166 .done();
167 }
168 }
169
170 Ok(())
171 }
172
173 /// Serializes a keyring, adding descriptive headers if armored.
174 fn serialize_keyring(sq: &Sq, file: &FileOrStdout, certs: Vec<Cert>,
175 binary: bool)
176 -> openpgp::Result<()> {
177 let mut output = file.create_safe(&sq)?;
178
179 if certs.len() > 1 {
180 let mut hint = sq.hint(format_args!(
181 "To extract a particular certificate from {}, use any of:",
182 file.path().map(|p| p.display().to_string())
183 .unwrap_or_else(|| "the stream".into())));
184
185 let path = file.path().map(|p| p.display().to_string())
186 .unwrap_or_else(|| "...".into());
187 for cert in &certs {
188 hint = hint.sq()
189 .arg("cert").arg("export")
190 .arg_value("--keyring", &path)
191 .arg_value("--cert", cert.fingerprint())
192 .done();
193 }
194 }
195
196 // Handle the easy options first. No armor no cry:
197 if binary {
198 for cert in certs {
199 cert.serialize(&mut output)?;
200 }
201 return Ok(());
202 }
203
204 // Just one Cert? Ez:
205 if certs.len() == 1 {
206 return certs[0].armored().serialize(&mut output);
207 }
208
209 // Then, collect the headers.
210 let mut headers = Vec::new();
211 for (i, cert) in certs.iter().enumerate() {
212 headers.push(format!("Key #{}", i));
213 headers.append(&mut cert.armor_headers());
214 }
215
216 let headers: Vec<_> = headers.iter()
217 .map(|value| ("Comment", value.as_str()))
218 .collect();
219 let mut output = armor::Writer::with_headers(&mut output,
220 armor::Kind::PublicKey,
221 headers)?;
222 for cert in certs {
223 cert.serialize(&mut output)?;
224 }
225 output.finalize()?;
226 Ok(())
227 }
228
229 /// Creates a non-exportable certification for the specified bindings.
230 ///
231 /// This does not import the certification or the certificate into
232 /// the certificate store.
233 fn certify(sq: &Sq,
234 emit_provenance_messages: bool,
235 signer: &mut dyn Signer, cert: &Cert, userids: &[UserID],
236 depth: u8, amount: usize)
237 -> Result<Cert>
238 {
239 let mut builder =
240 SignatureBuilder::new(SignatureType::GenericCertification)
241 .set_signature_creation_time(sq.time)?;
242
243 if depth != 0 || amount != 120 {
244 builder = builder.set_trust_signature(depth, amount.min(255) as u8)?;
245 }
246
247 builder = builder.set_exportable_certification(false)?;
248
249 let certifications = active_certification(
250 sq, cert,
251 userids.iter(),
252 signer.public())
253 .into_iter()
254 .map(|(userid, active_certification)| {
255 if let Some(_) = active_certification {
256 if emit_provenance_messages {
257 sq.info(format_args!(
258 "Provenance information for {}, {} \
259 exists and is current, not updating it",
260 cert.fingerprint(),
261 ui::Safe(userid)));
262 }
263 return vec![];
264 }
265
266 match builder.clone().sign_userid_binding(
267 signer,
268 cert.primary_key().key(),
269 &userid)
270 .with_context(|| {
271 format!("Creating certification for {}, {}",
272 cert.fingerprint(),
273 ui::Safe(userid))
274 })
275 {
276 Ok(sig) => {
277 if emit_provenance_messages {
278 sq.info(format_args!(
279 "Recorded provenance information \
280 for {}, {}",
281 cert.fingerprint(),
282 ui::Safe(userid)));
283 }
284 vec![ Packet::from(userid.clone()), Packet::from(sig) ]
285 }
286 Err(err) => {
287 let err = err.context(format!(
288 "Warning: recording provenance information \
289 for {}, {}",
290 cert.fingerprint(),
291 ui::Safe(userid)));
292 print_error_chain(&err);
293 vec![]
294 }
295 }
296 })
297 .collect::<Vec<Vec<Packet>>>()
298 .into_iter()
299 .flatten()
300 .collect::<Vec<Packet>>();
301
302 if certifications.is_empty() {
303 Ok(cert.clone())
304 } else {
305 Ok(cert.clone().insert_packets(certifications)?.0)
306 }
307 }
308
309 /// Certify the certificates using the specified CA.
310 ///
311 /// The certificates are certified for User IDs with the specified
312 /// email address. If no email address is specified, then all valid
313 /// User IDs are certified. The results are returned; they are not
314 /// imported into the certificate store.
315 ///
316 /// If a certificate cannot be certified for whatever reason, a
317 /// diagnostic is emitted, and the certificate is returned as is.
318 pub fn certify_downloads<'store, 'rstore>(sq: &mut Sq<'store, 'rstore>,
319 emit_provenance_messages: bool,
320 ca: Arc<LazyCert<'store>>,
321 certs: Vec<Cert>, email: Option<&str>)
322 -> Vec<Cert>
323 where 'store: 'rstore
324 {
325 let ca = || -> Result<_> {
326 let ca = ca.to_cert()?;
327
328 Ok(sq.get_certification_key(ca, None)?)
329 };
330 let mut ca_signer = match ca() {
331 Ok(signer) => signer,
332 Err(err) => {
333 let err = err.context(
334 "Warning: not recording provenance information, \
335 failed to load CA key");
336 if sq.verbose() {
337 print_error_chain(&err);
338 }
339 return certs;
340 }
341 };
342
343 // Normalize the email. If it is not valid, just return it as is.
344 let email = email.map(|email| {
345 match UserIDQueryParams::is_email(&email) {
346 Ok(email) => email,
347 Err(_) => email.to_string(),
348 }
349 });
350
351 let certs: Vec<Cert> = certs.into_iter().map(|cert| {
352 let vc = match cert.with_policy(sq.policy, sq.time) {
353 Err(err) => {
354 let err = err.context(format!(
355 "Warning: not recording provenance information \
356 for {}, not valid",
357 cert.fingerprint()));
358 if sq.verbose() {
359 print_error_chain(&err);
360 }
361 return cert;
362 }
363 Ok(vc) => vc,
364 };
365
366 let userids = if let Some(email) = email.as_ref() {
367 // Only the specified email address is authenticated.
368 let userids = vc.userids()
369 .filter_map(|ua| {
370 if let Ok(Some(e)) = ua.userid().email_normalized() {
371 if &e == email {
372 return Some(ua.userid().clone());
373 }
374 }
375 None
376 })
377 .collect::<Vec<UserID>>();
378
379 if userids.is_empty() {
380 if sq.verbose() {
381 sq.info(format_args!(
382 "Warning: not recording provenance information \
383 for {}, it does not contain a valid User ID with \
384 the specified email address ({:?})",
385 cert.fingerprint(),
386 email));
387 }
388 return cert;
389 }
390
391 userids
392 } else {
393 vc.userids().map(|ua| ua.userid().clone()).collect()
394 };
395
396 match certify(
397 sq, emit_provenance_messages,
398 &mut ca_signer, &cert, &userids[..],
399 0, sequoia_wot::FULLY_TRUSTED)
400 {
401 Ok(cert) => cert,
402 Err(err) => {
403 let err = err.context(format!(
404 "Warning: not recording provenance information \
405 for {}, failed to certify it",
406 cert.fingerprint()));
407 if sq.verbose() {
408 print_error_chain(&err);
409 }
410
411 cert
412 }
413 }
414 }).collect();
415
416 certs
417 }
418
419 #[derive(Clone)]
420 enum Query {
421 Handle(KeyHandle),
422 Address(String),
423 Url(Url),
424 }
425
426 impl From<Fingerprint> for Query {
427 fn from(fp: Fingerprint) -> Query {
428 Query::Handle(fp.into())
429 }
430 }
431
432 impl fmt::Display for Query {
433 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
434 match self {
435 Query::Handle(h) => write!(f, "{}", h),
436 Query::Address(a) => write!(f, "{}", a),
437 Query::Url(u) => write!(f, "{}", u),
438 }
439 }
440 }
441
442 impl Query {
443 /// Parses command line arguments to queries.
444 fn parse(args: &[String]) -> Result<Vec<Query>> {
445 args.iter().map(
446 |q| if let Ok(h) = q.parse::<KeyHandle>() {
447 Ok(Query::Handle(h))
448 } else if let Ok(Some(addr)) = UserID::from(q.as_str()).email() {
449 Ok(Query::Address(addr.to_string()))
450 } else if let Ok(url) = Url::parse(q.as_str()) {
451 Ok(Query::Url(url))
452 } else {
453 Err(anyhow::anyhow!(
454 "Query must be a fingerprint, a keyid, \
455 an http or https Url, or an email address: {:?}", q))
456 }).collect::<Result<Vec<Query>>>()
457 }
458
459 /// Parses command line arguments to queries suitable for key
460 /// servers.
461 fn parse_keyserver_queries(args: &[String]) -> Result<Vec<Query>> {
462 args.iter().map(
463 |q| if let Ok(h) = q.parse::<KeyHandle>() {
464 Ok(Query::Handle(h))
465 } else if let Ok(Some(addr)) = UserID::from(q.as_str()).email() {
466 Ok(Query::Address(addr.to_string()))
467 } else {
468 Err(anyhow::anyhow!(
469 "Query must be a fingerprint, a keyid, \
470 or an email address: {:?}", q))
471 }).collect::<Result<Vec<Query>>>()
472 }
473
474 /// Returns all known addresses and fingerprints of exportable
475 /// certificates as queries.
476 fn all_certs(sq: &Sq) -> Result<Vec<Query>> {
477 if let Some(store) = sq.cert_store()? {
478 let mut fingerprints = HashSet::new();
479 let mut addresses = HashSet::new();
480 for cert in store.certs().filter(
481 |c| c.to_cert().map(|c| cert_exportable(c)).unwrap_or(false))
482 {
483 fingerprints.insert(cert.fingerprint());
484 for address in cert.userids().filter_map(
485 |uid| uid.email().ok().flatten().map(|s| s.to_string()))
486 {
487 addresses.insert(address);
488 }
489 }
490
491 Ok(fingerprints.into_iter().map(|fp| Query::Handle(fp.into()))
492 .chain(addresses.into_iter().map(Query::Address))
493 .collect())
494 } else {
495 Err(anyhow::anyhow!("no known certificates"))
496 }
497 }
498
499
500 /// Returns all known addresses of exportable certificates as
501 /// queries.
502 fn all_addresses(sq: &Sq) -> Result<Vec<Query>> {
503 if let Some(store) = sq.cert_store()? {
504 let mut addresses = store.certs()
505 .filter(
506 |c| c.to_cert().map(|c| cert_exportable(c)).unwrap_or(false))
507 .flat_map(|cert| cert.userids().filter_map(
508 |uid| uid.email().ok().flatten().map(|s| s.to_string()))
509 .collect::<Vec<_>>())
510 .collect::<Vec<_>>();
511 addresses.sort_unstable();
512 addresses.dedup();
513 Ok(addresses.into_iter().map(Query::Address).collect())
514 } else {
515 Err(anyhow::anyhow!("no known certificates"))
516 }
517 }
518
519 /// Parses command line arguments to queries that only contain
520 /// email addresses.
521 fn parse_addresses(args: &[String]) -> Result<Vec<Query>> {
522 args.iter().map(
523 |q| if let Ok(Some(addr)) = UserID::from(q.as_str()).email() {
524 Ok(Query::Address(addr.to_string()))
525 } else {
526 Err(anyhow::anyhow!(
527 "Query must be a an email address: {:?}", q))
528 }).collect::<Result<Vec<Query>>>()
529 }
530
531 /// Returns the email address, if any.
532 fn as_address(&self) -> Option<&str> {
533 if let Query::Address(a) = self {
534 Some(a)
535 } else {
536 None
537 }
538 }
539
540 /// Returns the query if suitable for keyservers.
541 fn as_keyserver_query(&self) -> Option<&Query> {
542 match self {
543 Query::Address(_) => Some(self),
544 Query::Handle(_) => Some(self),
545 _ => None,
546 }
547 }
548 }
549
550 #[derive(Clone, PartialEq, Eq, PartialOrd, Ord)]
551 enum Method {
552 KeyServer(String),
553 WKD,
554 DANE,
555 Http(Url),
556 CertStore,
557 }
558
559 impl fmt::Display for Method {
560 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
561 match self {
562 Method::KeyServer(url) => write!(f, "{}", url),
563 Method::WKD => write!(f, "WKD"),
564 Method::DANE => write!(f, "DANE"),
565 Method::Http(_) => write!(f, "http"),
566 Method::CertStore => write!(f, "cert-store"),
567 }
568 }
569 }
570
571 impl Method {
572 // Returns the CA's certificate.
573 //
574 // This doesn't return an error, because not all methods have
575 // shadow CAs, and a missing CA is not a hard error.
576 fn ca<'store, 'rstore>(&self, sq: &Sq<'store, 'rstore>)
577 -> Option<Arc<LazyCert<'store>>>
578 where 'store: 'rstore
579 {
580 make_qprintln!(sq.quiet());
581
582 let ca = || -> Result<_> {
583 let certd = sq.certd_or_else()?;
584 let (cert, created) = match self {
585 Method::KeyServer(url) => {
586 let result = certd.shadow_ca_keyserver(url)?;
587
588 match result {
589 Some((cert, created)) => (cert, created),
590 None => {
591 if sq.verbose() {
592 weprintln!(
593 "Not recording provenance information: \
594 {} is not known to be a verifying \
595 keyserver",
596 url);
597 }
598 return Ok(None);
599 }
600 }
601 }
602 Method::WKD => certd.shadow_ca_wkd()?,
603 Method::DANE => certd.shadow_ca_dane()?,
604 Method::Http(url) =>
605 if let Some(r) = certd.shadow_ca_for_url(&url.to_string())? {
606 r
607 } else {
608 return Ok(None);
609 },
610 Method::CertStore => return Ok(None),
611 };
612
613 // Check that the data is a valid certificate. If not,
614 // bail sooner rather than later.
615 let _ = cert.to_cert()?;
616
617 Ok(Some((cert, created)))
618 };
619
620 let (cert, created) = match ca() {
621 Ok(Some((cert, created))) => (cert, created),
622 Ok(None) => return None,
623 Err(err) => {
624 let print_err = || {
625 weprintln!(
626 "Not recording provenance information: {}",
627 err);
628 };
629
630 if sq.verbose() {
631 print_err();
632 } else {
633 use std::sync::Once;
634 static MSG: Once = Once::new();
635 MSG.call_once(print_err);
636 }
637
638 return None;
639 }
640 };
641
642 if ! created {
643 // We didn't create it.
644 return Some(cert);
645 }
646
647 if sq.verbose() {
648 weprintln!(
649 "Created the local CA {} for certifying \
650 certificates downloaded from this service. \
651 Use `sq pki link authorize --unconstrained --amount N {}` \
652 to change how much it is trusted. Or \
653 `sq pki link retract {}` to disable it.",
654 if let Ok(uid) = cert.to_cert()
655 .and_then(|c| sq.best_userid(c, false).userid()
656 .map(ToString::to_string))
657 {
658 // We really want the self-signed, primary user
659 // ID.
660 uid
661 } else {
662 "invalid data".to_string()
663 },
664 cert.fingerprint(), cert.fingerprint());
665 } else {
666 use std::sync::Once;
667 static MSG: Once = Once::new();
668 MSG.call_once(|| {
669 qprintln!("Note: Created a local CA to record \
670 provenance information.\n\
671 Note: See `sq pki link list --ca` \
672 and `sq pki link --help` for more \
673 information.");
674 });
675 }
676
677 Some(cert)
678 }
679 }
680
681 struct Response {
682 query: Query,
683 method: Method,
684 results: Result<Vec<Result<Cert>>>,
685 }
686
687 impl Response {
688 /// Creates a progress bar.
689 fn progress_bar(sq: &Sq) -> ProgressBar {
690 if sq.verbose() || sq.batch {
691 ProgressBar::hidden()
692 } else {
693 ProgressBar::new(0)
694 }
695 }
696
697 /// Collects the responses, and displays failures.
698 ///
699 /// Certs are collected into `certs`, and references to all newly
700 /// discovered certs are returned.
701 ///
702 /// If `silent_errors` is given, then failure messages are
703 /// suppressed unless --verbose is given, or there was not a
704 /// single successful result.
705 async fn collect<'store, 'rstore>(
706 sq: &mut Sq<'store, 'rstore>,
707 mut responses: JoinSet<Response>,
708 certs: &mut BTreeMap<Fingerprint, (Cert, BTreeSet<Method>)>,
709 certify: bool,
710 silent_errors: bool,
711 pb: &mut ProgressBar,
712 )
713 -> Result<Vec<Fingerprint>>
714 where
715 'store: 'rstore
716 {
717 let mut new = Vec::new();
718
719 /// Merges `cert` into `acc`, adding its fingerprint to `new`
720 /// if the cert is new, or there are new user IDs.
721 fn merge(acc: &mut BTreeMap<Fingerprint, (Cert, BTreeSet<Method>)>,
722 new: &mut Vec<Fingerprint>,
723 method: Method,
724 cert: Cert)
725 -> Result<()>
726 {
727 use std::collections::btree_map::Entry;
728 match acc.entry(cert.fingerprint()) {
729 Entry::Occupied(e) => {
730 let (e, m) = e.into_mut();
731 let n_uids = e.userids().count();
732 *e = e.clone().merge_public(cert)?;
733 if e.userids().count() > n_uids {
734 new.push(e.fingerprint());
735 }
736 m.insert(method);
737 },
738 Entry::Vacant(e) => {
739 new.push(cert.fingerprint());
740 e.insert((cert, std::iter::once(method).collect()));
741 },
742 }
743 Ok(())
744 }
745
746 let mut errors = Vec::new();
747 while let Some(response) = responses.join_next().await {
748 pb.inc(1);
749 let response = response?;
750 match response.results {
751 Ok(returned_certs) => for cert in returned_certs {
752 match cert {
753 Ok(cert) => if ! certify {
754 merge(certs, &mut new,
755 response.method.clone(), cert)?;
756 } else { pb.suspend(|| -> Result<()> {
757 if let Some(ca) = response.method.ca(sq)
758 {
759 for cert in certify_downloads(
760 sq, true, ca, vec![cert], None)
761 {
762 merge(certs, &mut new,
763 response.method.clone(), cert)?;
764 }
765 } else {
766 merge(certs, &mut new,
767 response.method.clone(), cert)?;
768 }
769 Ok(())
770 })?},
771 Err(e) =>
772 errors.push((response.method.clone(),
773 response.query.clone(), e)),
774 }
775 },
776 Err(e) =>
777 errors.push((response.method, response.query, e)),
778 }
779 }
780
781 if ! silent_errors || sq.verbose() || certs.is_empty() {
782 for (method, query, e) in errors {
783 pb.suspend(|| weprintln!("{}: {}: {}", method, query, e));
784 }
785 }
786
787 if certs.is_empty() {
788 Err(anyhow::anyhow!("No cert found."))
789 } else {
790 Ok(new)
791 }
792 }
793
794 /// Either writes out a keyring or imports the certs.
795 fn import_or_emit(mut sq: Sq<'_, '_>,
796 output: Option<FileOrStdout>,
797 binary: bool,
798 certs: BTreeMap<Fingerprint, (Cert, BTreeSet<Method>)>)
799 -> Result<()>
800 {
801 make_qprintln!(sq.quiet());
802
803 qprintln!("\nFound {} related to the query:\n",
804 certs.len().of("certificate"));
805
806 let mut certs = certs.into_values()
807 .map(|(cert, methods)| {
808 let userid = sq.best_userid(&cert, true);
809 (userid, cert, methods)
810 })
811 .collect::<Vec<_>>();
812
813 // Reverse sort, i.e., most authenticated first.
814 certs.sort_unstable_by_key(|cert| usize::MAX - cert.0.trust_amount());
815
816 for (i, (userid, cert, methods)) in certs.iter().enumerate() {
817 if i > 0 {
818 qprintln!();
819 }
820
821 // Emit metadata.
822 qprintln!(initial_indent = " - ", "{}",
823 cert.fingerprint());
824 qprintln!(initial_indent = " - ", "{}", userid.display());
825 qprintln!(initial_indent = " - ", "created {}",
826 cert.primary_key().key().creation_time().convert());
827
828 match cert.with_policy(sq.policy, sq.time) {
829 Ok(vcert) => {
830 if let Err(e) = vcert.alive() {
831 qprintln!(initial_indent = " - ", "not live: {}", e);
832 }
833 match vcert.revocation_status() {
834 RevocationStatus::Revoked(sigs) => for s in sigs {
835 if let Some((reason, message)) =
836 s.reason_for_revocation()
837 {
838 qprintln!(initial_indent = " - ",
839 "revoked: {}, {}", reason,
840 ui::Safe(message));
841 } else {
842 qprintln!(initial_indent = " - ",
843 "revoked");
844 }
845 },
846
847 RevocationStatus::CouldBe(sigs) => for s in sigs {
848 if let Some((reason, message)) =
849 s.reason_for_revocation()
850 {
851 qprintln!(initial_indent = " - ",
852 "possibly revoked: {}, {}", reason,
853 ui::Safe(message));
854 } else {
855 qprintln!(initial_indent = " - ",
856 "possibly revoked");
857 }
858
859 match sq.lookup(s.get_issuers(),
860 None, false, true)
861 {
862 Ok(issuers) => for issuer in issuers {
863 qprintln!(initial_indent = " - ",
864 "by {}, {}",
865 issuer.fingerprint(),
866 sq.best_userid(&issuer, true)
867 .display());
868 },
869 Err(_) =>
870 qprintln!(initial_indent = " - ",
871 "by {}", s.get_issuers()[0]),
872 }
873 },
874
875 RevocationStatus::NotAsFarAsWeKnow => (),
876 }
877 },
878 Err(e) =>
879 qprintln!(initial_indent = " - ", "not valid: {}", e),
880 }
881
882 qprintln!(initial_indent = " - ", "found via: {}",
883 methods.into_iter().map(|m| m.to_string())
884 .collect::<Vec<_>>().join(", "));
885 }
886
887 let certs = certs.into_iter().map(|(_, cert, _)| cert).collect();
888
889 if let Some(file) = &output {
890 serialize_keyring(&sq, file, certs, binary)?;
891 } else {
892 import_certs(&mut sq, certs)?;
893 }
894
895 Ok(())
896 }
897 }
898
899 pub fn dispatch_search(mut sq: Sq, c: cli::network::search::Command)
900 -> Result<()>
901 {
902 if c.output.is_none() {
903 // We're going to save the output to the certificate store.
904 // Make sure it is enabled.
905 sq.cert_store_or_else()?;
906 }
907
908 let default_servers =
909 matches!(c.servers_source.unwrap(),
910 clap::parser::ValueSource::DefaultValue);
911
912 let http_client = http_client()?;
913 let servers = sq.config.key_servers(&c.servers, c.servers_source)
914 .map(|uri| KeyServer::with_client(uri, http_client.clone())
915 .with_context(|| format!("Malformed keyserver URI: {}", uri))
916 .map(Arc::new))
917 .collect::<Result<Vec<_>>>()?;
918
919 let iterations =
920 sq.config.network_search_iterations(c.iterations, c.iterations_source);
921 let use_wkd =
922 sq.config.network_search_use_wkd(c.use_wkd, c.use_wkd_source);
923 let use_dane =
924 sq.config.network_search_use_dane(c.use_dane, c.use_dane_source);
925
926 let mut seen_emails = HashSet::new();
927 let mut seen_fps = HashSet::new();
928 let mut seen_ids = HashSet::new();
929 let mut seen_urls = HashSet::new();
930 let mut queries = if c.all {
931 Query::all_certs(&sq)?
932 } else {
933 Query::parse(&c.query)?
934 };
935 let mut results = Default::default();
936 let mut pb = Response::progress_bar(&sq);
937
938 let rt = tokio::runtime::Runtime::new()?;
939 rt.block_on(async {
940 for _ in 0..iterations {
941 let cert_store = sq.cert_store()?;
942
943 let mut requests = JoinSet::new();
944 let mut converged = true;
945 std::mem::take(&mut queries).into_iter().for_each(|query| {
946 let new = match &query {
947 Query::Handle(KeyHandle::Fingerprint(fp)) =>
948 seen_fps.insert(fp.clone()),
949 Query::Handle(KeyHandle::KeyID(id)) =>
950 seen_ids.insert(id.clone()),
951 Query::Address(addr) =>
952 seen_emails.insert(addr.clone()),
953 Query::Url(url) =>
954 seen_urls.insert(url.clone()),
955 };
956
957 // Skip queries that we already did.
958 if ! new {
959 return;
960 }
961 converged = false;
962
963 if let Some(query) = query.as_keyserver_query() {
964 for ks in servers.iter().cloned() {
965 pb.inc_length(1);
966 let query = query.clone();
967 requests.spawn(async move {
968 let results = match query.clone() {
969 Query::Handle(h) => ks.get(h).await,
970 Query::Address(a) => ks.search(a).await,
971 Query::Url(_) => unreachable!(),
972 };
973 Response {
974 query,
975 results,
976 method: Method::KeyServer(
977 ks.url().as_str().to_string()),
978 }
979 });
980 }
981 }
982
983 if let Some(address) = query.as_address()
984 .filter(|_| use_wkd)
985 {
986 let a = address.to_string();
987 let http_client = http_client.clone();
988 pb.inc_length(1);
989 requests.spawn(async move {
990 let results =
991 wkd::get(&http_client, &a).await;
992 Response {
993 query: Query::Address(a),
994 results,
995 method: Method::WKD,
996 }
997 });
998 }
999
1000 if let Some(address) = query.as_address()
1001 .filter(|_| use_dane)
1002 {
1003 let a = address.to_string();
1004 pb.inc_length(1);
1005 requests.spawn(async move {
1006 let results = dane::get(&a).await;
1007 Response {
1008 query: Query::Address(a),
1009 results,
1010 method: Method::DANE,
1011 }
1012 });
1013 }
1014
1015 if let Query::Url(url) = &query {
1016 let query = query.clone();
1017 let http_client = http_client.clone();
1018 let url = url.clone();
1019 pb.inc_length(1);
1020 requests.spawn(async move {
1021 Response {
1022 query,
1023 results: match http_client.get(url.clone()).send().await
1024 {
1025 Ok(response) =>
1026 response.bytes().await
1027 .map_err(Into::into)
1028 .and_then(|b| CertParser::from_bytes(&b)
1029 .map(|cp| cp.collect())),
1030 Err(e) => Err(e.into()),
1031 },
1032 method: Method::Http(url),
1033 }
1034 });
1035 }
1036
1037 // Finally, we also consult the certificate store to
1038 // discover more identifiers. This is sync, but we use
1039 // the same mechanism to merge the result back in.
1040 if let Some(store) = &cert_store {
1041 pb.inc_length(1);
1042 let mut email_query = UserIDQueryParams::new();
1043 email_query.set_email(true);
1044 email_query.set_ignore_case(true);
1045
1046 let results = match &query {
1047 Query::Handle(h) => store.lookup_by_cert(h),
1048 Query::Address(a) => store.select_userid(&email_query, a),
1049 Query::Url(_) => return,
1050 }.map(|r| r.into_iter().map(|c| c.to_cert().cloned()).collect());
1051 requests.spawn(async move {
1052 Response {
1053 query,
1054 results,
1055 method: Method::CertStore,
1056 }
1057 });
1058 }
1059 });
1060
1061 if converged {
1062 return Result::Ok(());
1063 }
1064
1065 let new = Response::collect(
1066 &mut sq, requests, &mut results, c.output.is_none(),
1067 default_servers, &mut pb).await?;
1068
1069 // Expand certs to discover new identifiers to query.
1070 for (cert, _) in new.iter().filter_map(|fp| results.get(fp)) {
1071 queries.push(Query::Handle(cert.key_handle()));
1072
1073 for uid in cert.userids() {
1074 if let Ok(Some(addr)) = uid.userid().email() {
1075 queries.push(Query::Address(addr.into()));
1076 }
1077 }
1078 }
1079 }
1080
1081 Result::Ok(())
1082 })?;
1083 drop(pb);
1084
1085 // Release all thread pool resources.
1086 drop(rt);
1087
1088 Response::import_or_emit(sq, c.output, false, results)?;
1089 Ok(())
1090 }
1091
1092 pub fn dispatch_keyserver(
1093 mut sq: Sq,
1094 c: cli::network::keyserver::Command,
1095 matches: &ArgMatches,
1096 ) -> Result<()>
1097 {
1098 let servers_source = matches.value_source("servers").unwrap();
1099 let default_servers =
1100 matches!(servers_source, clap::parser::ValueSource::DefaultValue);
1101
1102 let servers = sq.config.key_servers(&c.servers, Some(servers_source))
1103 .map(|uri| KeyServer::with_client(uri, http_client()?)
1104 .with_context(|| format!("Malformed keyserver URI: {}", uri))
1105 .map(Arc::new))
1106 .collect::<Result<Vec<_>>>()?;
1107
1108 let rt = tokio::runtime::Runtime::new()?;
1109
1110 use crate::cli::network::keyserver::Subcommands::*;
1111 match c.subcommand {
1112 Search(c) => rt.block_on(async {
1113 if c.output.is_none() {
1114 // We're going to save the output to the certificate store.
1115 // Make sure it is enabled.
1116 sq.cert_store_or_else()?;
1117 }
1118
1119 let mut pb = Response::progress_bar(&sq);
1120 let queries = if c.all {
1121 Query::all_certs(&sq)?
1122 } else {
1123 Query::parse_keyserver_queries(&c.query)?
1124 };
1125
1126 let mut requests = tokio::task::JoinSet::new();
1127 queries.into_iter().for_each(|query| {
1128 for ks in servers.iter().cloned() {
1129 let query = query.clone();
1130 pb.inc_length(1);
1131 requests.spawn(async move {
1132 let results = match query.clone() {
1133 Query::Handle(h) => ks.get(h).await,
1134 Query::Address(a) => ks.search(a).await,
1135 Query::Url(_) => unreachable!(),
1136 };
1137 Response {
1138 query,
1139 results,
1140 method: Method::KeyServer(
1141 ks.url().as_str().to_string()),
1142 }
1143 });
1144 }
1145 });
1146
1147 let mut certs = Default::default();
1148 Response::collect(&mut sq, requests, &mut certs, c.output.is_none(),
1149 default_servers, &mut pb).await?;
1150 drop(pb);
1151 Response::import_or_emit(sq, c.output, false, certs)?;
1152 Result::Ok(())
1153 })?,
1154
1155 Publish(c) => rt.block_on(async {
1156 let o = &mut std::io::stdout();
1157 make_qprintln!(o, sq.quiet());
1158
1159 let (certs, errors) = sq.resolve_certs(
1160 &c.certs, TrustThreshold::Full)?;
1161 for error in errors.iter() {
1162 print_error_chain(error);
1163 }
1164 if ! errors.is_empty() {
1165 return Err(anyhow::anyhow!("Failed to resolve certificates"));
1166 }
1167
1168 let mut requests = tokio::task::JoinSet::new();
1169 for ks in servers.iter() {
1170 for cert in certs.iter().cloned() {
1171 let ks = ks.clone();
1172 requests.spawn(async move {
1173 let response = ks.send(&cert).await;
1174 (ks.url().to_string(), cert, response)
1175 });
1176 }
1177 }
1178
1179 let mut result = Ok(());
1180 while let Some(response) = requests.join_next().await {
1181 let (url, cert, response) = response?;
1182 match response {
1183 Ok(()) => {
1184 qprintln!("{}: ok", url);
1185 },
1186 Err(e) if default_servers
1187 && url == "hkps://mail-api.proton.me" =>
1188 {
1189 // Currently, the Proton keyserver is
1190 // read-only, but may change to accept updates
1191 // in the future. We still send them updates
1192 // by default, but we will not consider this
1193 // an error, and only print the message in
1194 // verbose mode.
1195 if sq.verbose() {
1196 wwriteln!(o, "{}: {}", url, e);
1197 }
1198 },
1199 Err(e) => {
1200 if url == "hkps://keys.mailvelope.com"
1201 && matches!(e.downcast_ref(),
1202 Some(net::Error::HttpStatus(
1203 StatusCode::BAD_REQUEST)))
1204 && cert.keys().with_policy(sq.policy, sq.time)
1205 .key_flags(KeyFlags::empty()
1206 .set_transport_encryption()
1207 .set_storage_encryption())
1208 .next().is_none()
1209 {
1210 qprintln!(
1211 "Warning: The Mailvelope key server \
1212 rejects certificates that are not \
1213 encryption-capable.");
1214 }
1215
1216 wwriteln!(o, "{}: {}", url, e);
1217 if result.is_ok() {
1218 result = Err((url, e));
1219 }
1220 },
1221 }
1222 }
1223
1224 result.map_err(|(_url, e)| e)
1225 })?,
1226 }
1227
1228 Ok(())
1229 }
1230
1231 pub fn dispatch_wkd(mut sq: Sq, c: cli::network::wkd::Command)
1232 -> Result<()>
1233 {
1234 let rt = tokio::runtime::Runtime::new()?;
1235
1236 use crate::cli::network::wkd::Subcommands::*;
1237 match c.subcommand {
1238 Search(c) => rt.block_on(async {
1239 if c.output.is_none() {
1240 // We're going to save the output to the certificate store.
1241 // Make sure it is enabled.
1242 sq.cert_store_or_else()?;
1243 }
1244
1245 let mut pb = Response::progress_bar(&sq);
1246 let http_client = http_client()?;
1247 let queries = if c.all {
1248 Query::all_addresses(&sq)?
1249 } else {
1250 Query::parse_addresses(&c.addresses)?
1251 };
1252 let mut requests = tokio::task::JoinSet::new();
1253 queries.into_iter().for_each(|query| {
1254 pb.inc_length(1);
1255 let http_client = http_client.clone();
1256 requests.spawn(async move {
1257 let results = wkd::get(
1258 &http_client,
1259 query.as_address().expect("parsed only addresses"))
1260 .await;
1261 Response {
1262 query,
1263 results,
1264 method: Method::WKD,
1265 }
1266 });
1267 });
1268
1269 let mut certs = Default::default();
1270 Response::collect(&mut sq, requests, &mut certs, c.output.is_none(),
1271 false, &mut pb).await?;
1272 drop(pb);
1273 Response::import_or_emit(sq, c.output, false, certs)?;
1274 Result::Ok(())
1275 })?,
1276
1277 Publish(mut c) => {
1278 let o = &mut std::io::stdout();
1279 make_qprintln!(o, sq.quiet());
1280
1281 use wkd::Variant;
1282 let cert_store = sq.cert_store()?;
1283
1284 // Make `--all` implicitly select all certs with a user ID
1285 // matching `--domain` that can be authenticated.
1286 if c.all {
1287 use cli::types::cert_designator::CertDesignator;
1288 c.certs.push(CertDesignator::Domain(c.domain.clone()));
1289 }
1290
1291 let (insert, errors) = sq.resolve_certs(
1292 &c.certs, TrustThreshold::Full)?;
1293 for error in errors.iter() {
1294 print_error_chain(error);
1295 }
1296 if ! errors.is_empty() {
1297 return Err(anyhow::anyhow!("Failed to resolve certificates"));
1298 }
1299
1300 let mut skipping = Vec::new();
1301 let mut insert: BTreeMap<_, _> = insert.into_iter()
1302 .filter(|cert| {
1303 if ! cert.with_policy(sq.policy, sq.time)
1304 .ok()
1305 .map(|vc| vc.userids().any(
1306 |u| u.userid().email().ok().flatten().map(
1307 |a| a.ends_with(&c.domain))
1308 .unwrap_or(false)))
1309 .unwrap_or(false)
1310 {
1311 skipping.push(cert.fingerprint());
1312 false // Drop.
1313 } else {
1314 true // Keep.
1315 }
1316 })
1317 .map(|c| (c.fingerprint(), c))
1318 .collect();
1319
1320 if ! skipping.is_empty() {
1321 qprintln!("Note: Skipping the following certificates because \
1322 they don't have a valid self-signed user ID in \
1323 {}:", c.domain);
1324 skipping.into_iter().for_each(|fipr| qprintln!(" - {}", fipr))
1325 }
1326
1327 if c.create && insert.is_empty() {
1328 sq.hint(format_args!(
1329 "You specified `--create`, but didn't specify any \
1330 certificates to insert. Try specifying `--all` to \
1331 insert all certificates that have an authenticated \
1332 user ID with an email address for {:?}.",
1333 c.domain));
1334 return Err(anyhow::anyhow!(
1335 "Cowardly refusing to create an empty WKD."));
1336 }
1337
1338 // Make `--rsync-path` imply `--rsync`.
1339 let rsync = c.rsync_path.take()
1340 .or_else(|| c.rsync.then_some("rsync".into()));
1341
1342 // Strategy: We transfer the WKD to a temporary directory,
1343 // read all the certs, update them from the local cert
1344 // store, re-create the WKD hierarchy, then transfer it
1345 // back.
1346 let wd = tempfile::TempDir::new()?;
1347
1348 // First, fetch the WKD.
1349 let fetch = wd.path().join("fetch");
1350 fs::create_dir(&fetch)?;
1351 let r = transfer(&rsync,
1352 &format!("{}/.well-known/openpgpkey", c.destination),
1353 &fetch.display().to_string())
1354 .with_context(|| {
1355 format!("failed to fetch the WKD from {}", c.destination)
1356 });
1357 if r.is_err() && ! c.create {
1358 return r;
1359 }
1360
1361 // Detect the variant by locating the policy file.
1362 let fetch = fetch.join("openpgpkey");
1363 let direct_policy = fetch.join("policy");
1364 let advanced_policy = fetch.join(&c.domain).join("policy");
1365
1366 if c.create && (direct_policy.exists()
1367 || advanced_policy.exists())
1368 {
1369 return Err(anyhow::anyhow!(
1370 "Cannot create WKD: {} already contains one",
1371 c.destination));
1372 }
1373
1374 let (variant, policy) = match (direct_policy.exists(),
1375 advanced_policy.exists())
1376 {
1377 (true, false) => (Variant::Direct, Some(direct_policy)),
1378 (false, true) => (Variant::Advanced, Some(advanced_policy)),
1379 (false, false) => if c.create {
1380 (c.method.unwrap_or_default().into(), None)
1381 } else {
1382 return Err(anyhow::anyhow!("No policy file found")
1383 .context(format!(
1384 "{} does not appear to be a \
1385 WKD, consider specifying `--create`",
1386 c.destination)))
1387 },
1388 (true, true) =>
1389 return Err(anyhow::anyhow!("Two policy files found")
1390 .context("Invalid WKD: both direct and advanced \
1391 WKD detected")),
1392 };
1393 let hu = match variant {
1394 Variant::Direct => fetch.join("hu"),
1395 Variant::Advanced => fetch.join(&c.domain).join("hu"),
1396 };
1397
1398 // Reports on certificate updates, or the lack thereof.
1399 let sq_ref = &sq;
1400 let mut printed_updating = false;
1401 let mut status = |cert: &Cert, msg: &str| {
1402 if ! printed_updating {
1403 printed_updating = true;
1404 qprintln!("Updating:");
1405 }
1406
1407 qprintln!(initial_indent = " - ", "{}", cert.fingerprint());
1408 qprintln!(initial_indent = " - ", "{}",
1409 sq_ref.best_userid(&cert, false).display());
1410 qprintln!(initial_indent = " - ", "{}", msg);
1411 qprintln!();
1412 };
1413
1414 // Now re-create the WKD hierarchy while updating the certs.
1415 let push = wd.path().join("push");
1416 let push_wk = push.join(".well-known");
1417 let push_openpgpkey = push_wk.join("openpgpkey");
1418 fs::create_dir(&push)?;
1419 let insert_ref = &mut insert;
1420 let mut number_of_changes = 0;
1421 let number_of_changes_ref = &mut number_of_changes;
1422 visit_dirs(&hu, &mut |entry: &DirEntry| -> Result<()> {
1423 let p = entry.path();
1424 for cert in CertParser::from_reader(fs::File::open(p)?)? {
1425 let mut cert = cert?;
1426
1427 let mut updated = false;
1428 let mut unchanged = false;
1429
1430 // Here we look for updates from the cert store
1431 // and merge them into any certificates in the
1432 // WKD. Below, we insert explicitly named
1433 // certificates. If a certificate exists in the
1434 // WKD and is explicitly named, we'll overwrite it
1435 // below. As such, we also handle explicitly
1436 // named certificates here.
1437 if let Some(update) = insert_ref.remove(&cert.fingerprint()) {
1438 let (cert_, updated_) = cert.insert_packets(
1439 update.into_packets())?;
1440 cert = cert_;
1441 if updated_ {
1442 updated = true;
1443 } else {
1444 unchanged = true;
1445 }
1446 }
1447
1448 // We still look for updates in the cert store:
1449 // the designated certificate could have been from
1450 // a file with updates that are not in the
1451 // certificate store.
1452 if let Some(update) = cert_store.as_ref().and_then(|cs| {
1453 cs.lookup_by_cert_fpr(&cert.fingerprint()).ok()
1454 }) {
1455 let (cert_, updated_) = cert.insert_packets(
1456 update.to_cert()?.clone().into_packets())?;
1457 cert = cert_;
1458 if updated_ {
1459 updated = true;
1460 } else {
1461 unchanged = true;
1462 }
1463 }
1464
1465 if updated {
1466 status(&cert, "updated");
1467 } else if unchanged {
1468 status(&cert, "unchanged");
1469 } else {
1470 status(&cert, "retained");
1471 }
1472
1473 if updated {
1474 wkd::insert(&push, &c.domain, variant, &cert)
1475 .with_context(|| {
1476 format!("Inserting {}, {}",
1477 cert.fingerprint(),
1478 sq.best_userid(&cert, true)
1479 .display())
1480 })?;
1481 *number_of_changes_ref += 1;
1482 }
1483 }
1484 Ok(())
1485 })?;
1486
1487 // Insert the new ones, if any.
1488 for (_fpr, cert) in insert.into_iter() {
1489 status(&cert, "inserted");
1490 wkd::insert(&push, &c.domain, variant, &cert)
1491 .with_context(|| {
1492 format!("Inserting {}, {}",
1493 cert.fingerprint(),
1494 sq.best_userid(&cert, true).display())
1495 })?;
1496 number_of_changes += 1;
1497 }
1498
1499 // Preserve the original policy file, if any.
1500 if let Some(policy) = policy {
1501 let path = match variant {
1502 Variant::Direct => push_openpgpkey.join("policy"),
1503 Variant::Advanced =>
1504 push_openpgpkey.join(&c.domain).join("policy"),
1505 };
1506
1507 fs::create_dir_all(
1508 path.parent().expect("at least two components"))?;
1509 fs::copy(policy, &path)
1510 .with_context(|| {
1511 format!("Updating {}", path.display())
1512 })?;
1513 }
1514
1515 if number_of_changes == 0 {
1516 qprintln!("No updates.");
1517 } else {
1518 // Finally, transfer the WKD hierarchy back.
1519 transfer(&rsync, &push_wk.display().to_string(),
1520 &format!("{}", c.destination))
1521 .with_context(|| {
1522 format!("failed to push updates to {}",
1523 c.destination)
1524 })?;
1525 qprintln!("{} applied.", number_of_changes.of("update"));
1526 }
1527 },
1528 }
1529
1530 Ok(())
1531 }
1532
1533 fn transfer(rsync_bin: &Option<PathBuf>, source: &str, destination: &str)
1534 -> Result<()>
1535 {
1536 if let Some(r) = rsync_bin {
1537 rsync(r, source, destination)
1538 } else {
1539 copy(source, destination)
1540 }
1541 }
1542
1543 fn copy(source: &str, destination: &str) -> Result<()> {
1544 let options = fs_extra::dir::CopyOptions::new()
1545 .overwrite(true);
1546
1547 std::fs::create_dir_all(destination)?;
1548 fs_extra::dir::copy(source, destination, &options)?;
1549 Ok(())
1550 }
1551
1552 fn rsync(rsync: &Path, source: &str, destination: &str) -> Result<()> {
1553 use std::process::Command;
1554
1555 let status = Command::new(rsync)
1556 .arg("--recursive")
1557 .arg(source)
1558 .arg(destination)
1559 .spawn()?
1560 .wait()?;
1561
1562 if status.success() {
1563 Ok(())
1564 } else {
1565 Err(anyhow::anyhow!("rsync failed"))
1566 }
1567 }
1568
1569 // one possible implementation of walking a directory only visiting files
1570 fn visit_dirs(dir: &Path, cb: &mut dyn FnMut(&DirEntry) -> Result<()>) -> Result<()> {
1571 if dir.is_dir() {
1572 for entry in fs::read_dir(dir)? {
1573 let entry = entry?;
1574 let path = entry.path();
1575 if path.is_dir() {
1576 visit_dirs(&path, cb)?;
1577 } else {
1578 cb(&entry)?;
1579 }
1580 }
1581 }
1582 Ok(())
1583 }
1584
1585 pub fn dispatch_dane(mut sq: Sq, c: cli::network::dane::Command)
1586 -> Result<()> {
1587 let rt = tokio::runtime::Runtime::new()?;
1588
1589 use crate::cli::network::dane::Subcommands::*;
1590 match c.subcommand {
1591 Generate(mut c) => {
1592 // Make `--all` implicitly select all certs with a user ID
1593 // matching `--domain` that can be authenticated.
1594 if c.all {
1595 use cli::types::cert_designator::CertDesignator;
1596 c.certs.push(CertDesignator::Domain(c.domain.clone()));
1597 }
1598
1599 let (certs, errors) = sq.resolve_certs(
1600 &c.certs, TrustThreshold::Full)?;
1601 for error in errors.iter() {
1602 print_error_chain(error);
1603 }
1604 if ! errors.is_empty() {
1605 return Err(anyhow::anyhow!("Failed to resolve certificates"));
1606 }
1607
1608 for cert in certs {
1609 let vc = cert.with_policy(sq.policy, sq.time)?;
1610
1611 use cli::network::dane::ResourceRecordType;
1612 let records = match c.typ {
1613 ResourceRecordType::OpenPGP =>
1614 dane::generate(&vc, &c.domain, c.ttl, c.size_limit)?,
1615 ResourceRecordType::Generic =>
1616 dane::generate_generic(&vc, &c.domain, c.ttl,
1617 c.size_limit)?,
1618 };
1619
1620 records.iter().for_each(|r| println!("{}", r));
1621 }
1622 },
1623 Search(c) => rt.block_on(async {
1624 if c.output.is_none() {
1625 // We're going to save the output to the certificate store.
1626 // Make sure it is enabled.
1627 sq.cert_store_or_else()?;
1628 }
1629
1630 let mut pb = Response::progress_bar(&sq);
1631 let queries = if c.all {
1632 Query::all_addresses(&sq)?
1633 } else {
1634 Query::parse_addresses(&c.addresses)?
1635 };
1636 let mut requests = tokio::task::JoinSet::new();
1637 queries.into_iter().for_each(|query| {
1638 pb.inc_length(1);
1639 requests.spawn(async move {
1640 let results = dane::get(
1641 query.as_address().expect("parsed only addresses"))
1642 .await;
1643 Response {
1644 query,
1645 results,
1646 method: Method::DANE,
1647 }
1648 });
1649 });
1650
1651 let mut certs = Default::default();
1652 Response::collect(&mut sq, requests, &mut certs, c.output.is_none(),
1653 false, &mut pb).await?;
1654 drop(pb);
1655 Response::import_or_emit(sq, c.output, false, certs)?;
1656 Result::Ok(())
1657 })?,
1658 }
1659
1660 Ok(())
1661 }
1662
1663 /// Makes a http client.
1664 fn http_client() -> Result<net::reqwest::Client> {
1665 Ok(net::reqwest::Client::builder()
1666 .user_agent(USER_AGENT)
1667 .connect_timeout(CONNECT_TIMEOUT)
1668 .timeout(REQUEST_TIMEOUT)
1669 .build()?)
1670 }