|
| 1 | +pub extern crate openssl; |
| 2 | +extern crate postgres; |
| 3 | + |
| 4 | +use openssl::error::ErrorStack; |
| 5 | +use openssl::ssl::{ConnectConfiguration, SslConnector, SslMethod, SslStream}; |
| 6 | +use postgres::tls::{Stream, TlsHandshake, TlsStream}; |
| 7 | +use std::error::Error; |
| 8 | +use std::fmt; |
| 9 | +use std::io::{self, Read, Write}; |
| 10 | + |
| 11 | +#[cfg(test)] |
| 12 | +mod test; |
| 13 | + |
| 14 | +pub struct OpenSsl { |
| 15 | + connector: SslConnector, |
| 16 | + config: Box<Fn(&mut ConnectConfiguration) -> Result<(), ErrorStack> + Sync + Send>, |
| 17 | +} |
| 18 | + |
| 19 | +impl fmt::Debug for OpenSsl { |
| 20 | + fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result { |
| 21 | + fmt.debug_struct("OpenSsl").finish() |
| 22 | + } |
| 23 | +} |
| 24 | + |
| 25 | +impl OpenSsl { |
| 26 | + pub fn new() -> Result<OpenSsl, ErrorStack> { |
| 27 | + let connector = SslConnector::builder(SslMethod::tls())?.build(); |
| 28 | + Ok(OpenSsl::with_connector(connector)) |
| 29 | + } |
| 30 | + |
| 31 | + pub fn with_connector(connector: SslConnector) -> OpenSsl { |
| 32 | + OpenSsl { |
| 33 | + connector, |
| 34 | + config: Box::new(|_| Ok(())), |
| 35 | + } |
| 36 | + } |
| 37 | + |
| 38 | + pub fn callback<F>(&mut self, f: F) |
| 39 | + where |
| 40 | + F: Fn(&mut ConnectConfiguration) -> Result<(), ErrorStack> + 'static + Sync + Send, |
| 41 | + { |
| 42 | + self.config = Box::new(f); |
| 43 | + } |
| 44 | +} |
| 45 | + |
| 46 | +impl TlsHandshake for OpenSsl { |
| 47 | + fn tls_handshake( |
| 48 | + &self, |
| 49 | + domain: &str, |
| 50 | + stream: Stream, |
| 51 | + ) -> Result<Box<TlsStream>, Box<Error + Sync + Send>> { |
| 52 | + let mut ssl = self.connector.configure()?; |
| 53 | + (self.config)(&mut ssl)?; |
| 54 | + let stream = ssl.connect(domain, stream)?; |
| 55 | + |
| 56 | + Ok(Box::new(OpenSslStream(stream))) |
| 57 | + } |
| 58 | +} |
| 59 | + |
| 60 | +#[derive(Debug)] |
| 61 | +struct OpenSslStream(SslStream<Stream>); |
| 62 | + |
| 63 | +impl Read for OpenSslStream { |
| 64 | + fn read(&mut self, buf: &mut [u8]) -> io::Result<usize> { |
| 65 | + self.0.read(buf) |
| 66 | + } |
| 67 | +} |
| 68 | + |
| 69 | +impl Write for OpenSslStream { |
| 70 | + fn write(&mut self, buf: &[u8]) -> io::Result<usize> { |
| 71 | + self.0.write(buf) |
| 72 | + } |
| 73 | + |
| 74 | + fn flush(&mut self) -> io::Result<()> { |
| 75 | + self.0.flush() |
| 76 | + } |
| 77 | +} |
| 78 | + |
| 79 | +impl TlsStream for OpenSslStream { |
| 80 | + fn get_ref(&self) -> &Stream { |
| 81 | + self.0.get_ref() |
| 82 | + } |
| 83 | + |
| 84 | + fn get_mut(&mut self) -> &mut Stream { |
| 85 | + self.0.get_mut() |
| 86 | + } |
| 87 | +} |
0 commit comments