Debian Codegraph @

src/net/tls/tls_native_tls.rs

raw symbols SCIP
1 use std::io::{self, Read, Write};
2
3 use crate::io::ReadBuf;
4 use crate::net::tls::util::StdSocket;
5 use crate::net::tls::TlsConfig;
6 use crate::net::Socket;
7 use crate::Error;
8
9 use native_tls::{HandshakeError, Identity};
10 use std::task::{Context, Poll};
11
12 pub struct NativeTlsSocket<S: Socket> {
13 stream: native_tls::TlsStream<StdSocket<S>>,
14 }
15
16 impl<S: Socket> Socket for NativeTlsSocket<S> {
17 fn try_read(&mut self, buf: &mut dyn ReadBuf) -> io::Result<usize> {
18 self.stream.read(buf.init_mut())
19 }
20
21 fn try_write(&mut self, buf: &[u8]) -> io::Result<usize> {
22 self.stream.write(buf)
23 }
24
25 fn poll_read_ready(&mut self, cx: &mut Context<'_>) -> Poll<io::Result<()>> {
26 self.stream.get_mut().poll_ready(cx)
27 }
28
29 fn poll_write_ready(&mut self, cx: &mut Context<'_>) -> Poll<io::Result<()>> {
30 self.stream.get_mut().poll_ready(cx)
31 }
32
33 fn poll_shutdown(&mut self, cx: &mut Context<'_>) -> Poll<io::Result<()>> {
34 match self.stream.shutdown() {
35 Err(e) if e.kind() == io::ErrorKind::WouldBlock => self.stream.get_mut().poll_ready(cx),
36 ready => Poll::Ready(ready),
37 }
38 }
39 }
40
41 pub async fn handshake<S: Socket>(
42 socket: S,
43 config: TlsConfig<'_>,
44 ) -> crate::Result<NativeTlsSocket<S>> {
45 let mut builder = native_tls::TlsConnector::builder();
46
47 builder
48 .danger_accept_invalid_certs(config.accept_invalid_certs)
49 .danger_accept_invalid_hostnames(config.accept_invalid_hostnames);
50
51 if let Some(root_cert_path) = config.root_cert_path {
52 let data = root_cert_path.data().await?;
53 builder.add_root_certificate(native_tls::Certificate::from_pem(&data).map_err(Error::tls)?);
54 }
55
56 // authentication using user's key-file and its associated certificate
57 if let (Some(cert_path), Some(key_path)) = (config.client_cert_path, config.client_key_path) {
58 let cert_path = cert_path.data().await?;
59 let key_path = key_path.data().await?;
60 let identity = Identity::from_pkcs8(&cert_path, &key_path).map_err(Error::tls)?;
61 builder.identity(identity);
62 }
63
64 let connector = builder.build().map_err(Error::tls)?;
65
66 let mut mid_handshake = match connector.connect(config.hostname, StdSocket::new(socket)) {
67 Ok(tls_stream) => return Ok(NativeTlsSocket { stream: tls_stream }),
68 Err(HandshakeError::Failure(e)) => return Err(Error::tls(e)),
69 Err(HandshakeError::WouldBlock(mid_handshake)) => mid_handshake,
70 };
71
72 loop {
73 mid_handshake.get_mut().ready().await?;
74
75 match mid_handshake.handshake() {
76 Ok(tls_stream) => return Ok(NativeTlsSocket { stream: tls_stream }),
77 Err(HandshakeError::Failure(e)) => return Err(Error::tls(e)),
78 Err(HandshakeError::WouldBlock(mid_handshake_)) => {
79 mid_handshake = mid_handshake_;
80 }
81 }
82 }
83 }