Skip to content

Commit e7b883d

Browse files
zsckmattnenterprise
authored andcommitted
Add a secure_with_ssl method to FtpStream so that users can supply their own SSL configuration (#44)
1 parent 3423aaf commit e7b883d

File tree

1 file changed

+30
-7
lines changed

1 file changed

+30
-7
lines changed

src/ftp.rs

Lines changed: 30 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -7,7 +7,7 @@ use regex::Regex;
77
use chrono::{DateTime, UTC};
88
use chrono::offset::TimeZone;
99
#[cfg(feature = "secure")]
10-
use openssl::ssl::{Ssl, SslContext, SslMethod, SslStream};
10+
use openssl::ssl::{Ssl, SslContext, SslMethod, SslStream, IntoSsl};
1111
use super::data_stream::DataStream;
1212
use super::status;
1313
use super::types::FileType;
@@ -75,6 +75,35 @@ impl FtpStream {
7575
///
7676
#[cfg(feature = "secure")]
7777
pub fn secure(mut self) -> (FtpStream, Result<()>) {
78+
// Initialize SSL with a default context and make secure the stream.
79+
let ssl = match Ssl::new(&SSL_CONTEXT) {
80+
Ok(ssl) => ssl,
81+
Err(e) => panic!("error: cannot create SSL context: {}", e)
82+
};
83+
self.secure_with_ssl(ssl)
84+
}
85+
86+
/// Switch to a secure mode if possible, using a provided SSL configuration.
87+
/// This method does nothing if the connect is already secured.
88+
///
89+
/// ## Panics
90+
///
91+
/// Panics if the plain TCP connection cannot be switched to TLS mode.
92+
///
93+
/// ## Example
94+
///
95+
/// ```
96+
/// use ftp::FtpStream;
97+
/// use openssl::ssl::*;
98+
///
99+
/// // Create an SslContext with a custom cert.
100+
/// let mut ctx = SslContext::new(SslMethod::Sslv23).unwrap();
101+
/// let _ = ctx.set_CA_file("/path/to/a/cert.pem").unwrap();
102+
/// let mut ftp_stream = FtpStream::connect("127.0.0.1:21").unwrap();
103+
/// let (mut ftp_stream, _) = ftp_stream.secure_with_ssl(ctx);
104+
/// ```
105+
#[cfg(feature = "secure")]
106+
pub fn secure_with_ssl<S: IntoSsl>(mut self, ssl: S) -> (FtpStream, Result<()>) {
78107
let secured = self.reader.get_ref().is_ssl();
79108
if secured {
80109
(self, Ok(()))
@@ -90,12 +119,6 @@ impl FtpStream {
90119
return (self, Err(e));
91120
}
92121

93-
// Initialize SSL and make the opened stream secured
94-
let ssl = match Ssl::new(&SSL_CONTEXT) {
95-
Ok(ssl) => ssl,
96-
Err(e) => panic!("error: cannot create SSL context: {}", e)
97-
};
98-
99122
let stream = match SslStream::connect(ssl, self.reader.into_inner().into_tcp_stream()) {
100123
Ok(stream) => stream,
101124
Err(e) => panic!("error: cannot open SSL connection: {}", e)

0 commit comments

Comments
 (0)