1#![doc(html_favicon_url = "https://docs.sequoia-pgp.org/favicon.png")]
52#![doc(html_logo_url = "https://docs.sequoia-pgp.org/logo.svg")]
53#![warn(missing_docs)]
54
55use std::sync::Arc;
56
57#[cfg(feature = "isahc")]
60pub use isahc;
61#[cfg(feature = "reqwest")]
62pub use reqwest;
63
64use percent_encoding::{percent_encode, AsciiSet, CONTROLS};
65
66use url::Url;
67
68use sequoia_openpgp::{
69 self as openpgp,
70 cert::{Cert, CertParser},
71 KeyHandle,
72 packet::UserID,
73 parse::Parse,
74 serialize::Serialize,
75};
76
77#[macro_use] mod macros;
78pub mod dane;
79mod email;
80pub mod updates;
81pub mod wkd;
82
83const KEYSERVER_ENCODE_SET: &AsciiSet =
85 &CONTROLS.add(b' ').add(b'"').add(b'#').add(b'<').add(b'>').add(b'`')
87 .add(b'?').add(b'{').add(b'}')
88 .add(b'-').add(b'+').add(b'/');
91const KEYSERVER_GET_ENCODE_SET: &AsciiSet = &KEYSERVER_ENCODE_SET
95 .add(b'&').add(b'=')
97 .add(b'%');
99
100#[derive(Clone)]
102pub struct KeyServer {
103 client: Arc<dyn HttpClient>,
104 url: Url,
106 request_url: Url,
108}
109
110assert_send_and_sync!(KeyServer);
111
112#[cfg(any(feature = "reqwest", feature = "isahc"))]
113impl Default for KeyServer {
114 fn default() -> Self {
115 Self::new("hkps://keys.openpgp.org/").unwrap()
116 }
117}
118
119impl KeyServer {
120 #[allow(unreachable_code)]
121 #[cfg(any(feature = "reqwest", feature = "isahc"))]
122 pub fn new(url: &str) -> Result<Self> {
124 #[cfg(feature = "reqwest")]
125 {
126 return Self::with_client(url, Box::new(reqwest::Client::new()));
127 }
128 #[cfg(feature = "isahc")]
129 {
130 Self::with_client(url, Box::new(isahc::HttpClient::new()?))
131 }
132 }
133
134 pub fn with_client(url: &str, client: Box<dyn HttpClient>) -> Result<Self> {
136 let client = client.into();
137 let url = Url::parse(url)?;
138
139 let s = url.scheme();
140 match s {
141 "hkp" => (),
142 "hkps" => (),
143 _ => return Err(Error::MalformedUrl.into()),
144 }
145
146 let request_url =
147 format!("{}://{}:{}",
148 match s {"hkp" => "http", "hkps" => "https",
149 _ => unreachable!()},
150 url.host().ok_or(Error::MalformedUrl)?,
151 match s {
152 "hkp" => url.port().or(Some(11371)),
153 "hkps" => url.port().or(Some(443)),
154 _ => unreachable!(),
155 }.unwrap()).parse()?;
156
157 Ok(KeyServer { client, url, request_url })
158 }
159
160 pub fn url(&self) -> &Url {
162 &self.url
163 }
164
165 pub async fn get<H: Into<KeyHandle>>(&self, handle: H)
172 -> Result<Vec<Result<Cert>>>
173 {
174 let handle = handle.into();
175 let url = self.request_url.join(&format!(
176 "pks/lookup?op=get&options=mr&search=0x{:X}",
177 handle
178 ))?;
179
180 let body = Box::into_pin(self.client.get(url)).await?;
181 let certs = CertParser::from_bytes(&body)?.collect();
182 Ok(certs)
183 }
184
185 pub async fn search<U: Into<UserID>>(&self, userid: U)
198 -> Result<Vec<Result<Cert>>>
199 {
200 let userid = userid.into();
201 let email = userid.email().and_then(|addr| addr.ok_or_else(||
202 openpgp::Error::InvalidArgument(
203 "UserID does not contain an email address".into()).into()))?;
204 let url = self.request_url.join(
205 &format!("pks/lookup?op=get&options=mr&search={}",
206 percent_encode(email.as_bytes(), KEYSERVER_GET_ENCODE_SET)
207 ))?;
208
209 let body = Box::into_pin(self.client.get(url)).await?;
210 let certs = CertParser::from_bytes(&body)?.collect();
211 Ok(certs)
212 }
213
214 pub async fn send(&self, key: &Cert) -> Result<()> {
216 use sequoia_openpgp::armor::{Writer, Kind};
217
218 let url = self.request_url.join("pks/add")?;
219 let mut w = Writer::new(Vec::new(), Kind::PublicKey)?;
220 key.serialize(&mut w)?;
221
222 let armored_blob = w.finalize()?;
223
224 let mut post_data = b"keytext=".to_vec();
226 post_data.extend_from_slice(percent_encode(&armored_blob, KEYSERVER_ENCODE_SET)
227 .collect::<String>().as_bytes());
228
229 Box::into_pin(self
230 .client
231 .post(url, post_data))
232 .await
233
234 }
235}
236
237pub type Result<T> = ::std::result::Result<T, anyhow::Error>;
239
240#[derive(thiserror::Error, Debug)]
241#[non_exhaustive]
243pub enum Error {
244 #[error("Cert not found")]
246 NotFound,
247 #[error("Malformed URL; expected hkp: or hkps:")]
249 MalformedUrl,
250 #[error("Malformed response from server")]
252 MalformedResponse,
253 #[error("Protocol violation")]
255 ProtocolViolation,
256 #[error("server returned status {0}")]
258 HttpStatus(http::StatusCode),
259 #[error(transparent)]
261 UrlError(#[from] url::ParseError),
262 #[error(transparent)]
264 HttpError(#[from] http::Error),
265
266 #[error("Malformed email address {0}")]
269 MalformedEmail(String),
270
271 #[error("Email address {0} not found in Cert's userids")]
273 EmailNotInUserids(String),
274}
275
276pub trait HttpClient: Send + Sync {
278 fn get(&'_ self, url: Url) -> Box<dyn std::future::Future<Output = Result<Vec<u8>>> + Send + '_>;
280 fn post(&'_ self, url: Url, post_data: Vec<u8>) -> Box<dyn std::future::Future<Output = Result<()>> + Send + '_>;
282}
283
284#[cfg(feature = "reqwest")]
285impl HttpClient for reqwest::Client {
286 fn get(&'_ self, url: Url) -> Box<dyn std::future::Future<Output = Result<Vec<u8>>> + Send + '_> {
287 Box::new(async {
288 let res = self.get(url).send().await?;
289 match res.status() {
290 http::StatusCode::OK => {
291 Ok(res.bytes().await?.to_vec())
292 }
293 http::StatusCode::NOT_FOUND => Err(Error::NotFound.into()),
294 n => Err(Error::HttpStatus(n).into()),
295 }
296 })
297 }
298
299 fn post(&'_ self, url: Url, post_data: Vec<u8>) -> Box<dyn std::future::Future<Output = Result<()>> + Send + '_> {
300 Box::new(async {
301 let res = self
302 .post(url)
303 .header("content-type", "application/x-www-form-urlencoded")
304 .header("content-length", post_data.len().to_string())
305 .body(post_data)
306 .send()
307 .await?;
308
309 match res.status() {
310 http::StatusCode::OK => Ok(()),
311 http::StatusCode::NOT_FOUND => Err(Error::ProtocolViolation.into()),
312 n => Err(Error::HttpStatus(n).into()),
313 }
314 })
315 }
316}
317
318#[cfg(feature = "isahc")]
319impl HttpClient for isahc::HttpClient {
320 fn get(
321 &'_ self,
322 url: Url,
323 ) -> Box<dyn std::future::Future<Output = Result<Vec<u8>>> + Send + '_> {
324 use isahc::AsyncReadResponseExt;
325 Box::new(async move {
326 let mut res = self.get_async(url.as_str()).await?;
327 match res.status() {
328 http::StatusCode::OK => Ok(res.bytes().await?.to_vec()),
329 http::StatusCode::NOT_FOUND => Err(Error::NotFound.into()),
330 n => Err(Error::HttpStatus(n).into()),
331 }
332 })
333 }
334
335 fn post(
336 &'_ self,
337 url: Url,
338 post_data: Vec<u8>,
339 ) -> Box<dyn std::future::Future<Output = Result<()>> + Send + '_> {
340 Box::new(async move {
341 let request = isahc::Request::post(url.as_str())
342 .header("Content-Type", "application/x-www-form-urlencoded")
343 .header("Content-Length", post_data.len().to_string())
344 .body(post_data)?;
345 let res = self.send_async(request).await?;
346
347 match res.status() {
348 http::StatusCode::OK => Ok(()),
349 http::StatusCode::NOT_FOUND => Err(Error::ProtocolViolation.into()),
350 n => Err(Error::HttpStatus(n).into()),
351 }
352 })
353 }
354}
355
356#[cfg(test)]
357mod tests {
358 use super::*;
359
360 #[cfg(any(feature = "reqwest", feature = "isahc"))]
361 #[test]
362 fn urls() {
363 assert!(KeyServer::new("keys.openpgp.org").is_err());
364 assert!(KeyServer::new("hkp://keys.openpgp.org").is_ok());
365 assert!(KeyServer::new("hkps://keys.openpgp.org").is_ok());
366 }
367
368 #[test]
369 fn encoding() {
370 assert_eq!(
371 percent_encode(b"alice@example.com",
372 KEYSERVER_GET_ENCODE_SET)
373 .collect::<String>(),
374 "alice@example.com"
375 );
376 assert_eq!(
377 percent_encode(b"alice+tag@example.com",
378 KEYSERVER_GET_ENCODE_SET)
379 .collect::<String>(),
380 "alice%2Btag@example.com"
381 );
382 assert_eq!(
383 percent_encode(b"alice+tag&role=admin%@example.com",
384 KEYSERVER_GET_ENCODE_SET)
385 .collect::<String>(),
386 "alice%2Btag%26role%3Dadmin%25@example.com"
387 );
388
389 }
390}