Skip to content

Commit eb3a8c6

Browse files
committed
wip(ssl-verify): add a function argument to NetworkConnector::connect() to create a context
1 parent ad22d79 commit eb3a8c6

File tree

5 files changed

+64
-31
lines changed

5 files changed

+64
-31
lines changed

src/client/request.rs

Lines changed: 13 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -2,6 +2,7 @@
22
use std::io::{BufferedWriter, IoResult};
33

44
use url::Url;
5+
use openssl::ssl::SslContext;
56

67
use method;
78
use method::Method::{Get, Post, Delete, Put, Patch, Head, Options};
@@ -42,11 +43,11 @@ impl<W> Request<W> {
4243
impl Request<Fresh> {
4344
/// Create a new client request.
4445
pub fn new(method: method::Method, url: Url) -> HttpResult<Request<Fresh>> {
45-
Request::with_stream::<HttpStream>(method, url)
46+
Request::with_stream::<HttpStream, fn() -> IoResult<SslContext>, SslContext>(method, url, HttpStream::ssl_context)
4647
}
4748

4849
/// Create a new client request with a specific underlying NetworkStream.
49-
pub fn with_stream<S: NetworkConnector>(method: method::Method, url: Url) -> HttpResult<Request<Fresh>> {
50+
pub fn with_stream<S: NetworkConnector<T>, F: FnOnce() -> IoResult<T>, T>(method: method::Method, url: Url, context: F) -> HttpResult<Request<Fresh>> {
5051
debug!("{} {}", method, url);
5152
let host = match url.serialize_host() {
5253
Some(host) => host,
@@ -59,7 +60,7 @@ impl Request<Fresh> {
5960
};
6061
debug!("port={}", port);
6162

62-
let stream: S = try!(NetworkConnector::connect((host[], port), url.scheme.as_slice()));
63+
let stream: S = try!(NetworkConnector::connect((host[], port), &*url.scheme, context));
6364
let stream = ThroughWriter(BufferedWriter::new(box stream as Box<NetworkStream + Send>));
6465

6566
let mut headers = Headers::new();
@@ -207,16 +208,21 @@ impl Writer for Request<Streaming> {
207208
#[cfg(test)]
208209
mod tests {
209210
use std::boxed::BoxAny;
211+
use std::io::IoResult;
210212
use std::str::from_utf8;
211213
use url::Url;
212214
use method::Method::{Get, Head};
213215
use mock::MockStream;
214216
use super::Request;
215217

218+
fn noop() -> IoResult<()> {
219+
Ok(())
220+
}
221+
216222
#[test]
217223
fn test_get_empty_body() {
218-
let req = Request::with_stream::<MockStream>(
219-
Get, Url::parse("http://example.dom").unwrap()
224+
let req = Request::with_stream::<MockStream, fn() -> IoResult<()>, ()>(
225+
Get, Url::parse("http://example.dom").unwrap(), noop
220226
).unwrap();
221227
let req = req.start().unwrap();
222228
let stream = *req.body.end().unwrap().into_inner().downcast::<MockStream>().unwrap();
@@ -228,8 +234,8 @@ mod tests {
228234

229235
#[test]
230236
fn test_head_empty_body() {
231-
let req = Request::with_stream::<MockStream>(
232-
Head, Url::parse("http://example.dom").unwrap()
237+
let req = Request::with_stream::<MockStream, fn() -> IoResult<()>, ()>(
238+
Head, Url::parse("http://example.dom").unwrap(), noop
233239
).unwrap();
234240
let req = req.start().unwrap();
235241
let stream = *req.body.end().unwrap().into_inner().downcast::<MockStream>().unwrap();

src/http.rs

Lines changed: 25 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -190,6 +190,31 @@ impl<W: Writer> HttpWriter<W> {
190190
}
191191
}
192192

193+
/// Access the inner Writer.
194+
#[inline]
195+
pub fn get_ref<'a>(&'a self) -> &'a W {
196+
match *self {
197+
ThroughWriter(ref w) => w,
198+
ChunkedWriter(ref w) => w,
199+
SizedWriter(ref w, _) => w,
200+
EmptyWriter(ref w) => w,
201+
}
202+
}
203+
204+
/// Access the inner Writer mutably.
205+
///
206+
/// Warning: You should not write to this directly, as you can corrupt
207+
/// the state.
208+
#[inline]
209+
pub fn get_mut<'a>(&'a mut self) -> &'a mut W {
210+
match *self {
211+
ThroughWriter(ref mut w) => w,
212+
ChunkedWriter(ref mut w) => w,
213+
SizedWriter(ref mut w, _) => w,
214+
EmptyWriter(ref mut w) => w,
215+
}
216+
}
217+
193218
/// Ends the HttpWriter, and returns the underlying Writer.
194219
///
195220
/// A final `write()` is called with an empty message, and then flushed.

src/lib.rs

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,5 @@
11
#![feature(macro_rules, phase, default_type_params, if_let, slicing_syntax,
2-
tuple_indexing, globs)]
2+
tuple_indexing, globs, unboxed_closures)]
33
#![deny(missing_docs)]
44
#![deny(warnings)]
55
#![experimental]

src/mock.rs

Lines changed: 2 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -61,14 +61,13 @@ impl Writer for MockStream {
6161
}
6262

6363
impl NetworkStream for MockStream {
64-
6564
fn peer_name(&mut self) -> IoResult<SocketAddr> {
6665
Ok(from_str("127.0.0.1:1337").unwrap())
6766
}
6867
}
6968

70-
impl NetworkConnector for MockStream {
71-
fn connect<To: ToSocketAddr>(_addr: To, _scheme: &str) -> IoResult<MockStream> {
69+
impl NetworkConnector<()> for MockStream {
70+
fn connect<To: ToSocketAddr, F: FnOnce() -> IoResult<()>>(_addr: To, _scheme: &str, _: F) -> IoResult<MockStream> {
7271
Ok(MockStream::new())
7372
}
7473
}

src/net.rs

Lines changed: 23 additions & 20 deletions
Original file line numberDiff line numberDiff line change
@@ -9,7 +9,6 @@ use std::io::net::ip::{SocketAddr, ToSocketAddr};
99
use std::io::net::tcp::{TcpStream, TcpListener, TcpAcceptor};
1010
use std::mem::{mod, transmute, transmute_copy};
1111
use std::raw::{mod, TraitObject};
12-
use std::sync::{Arc, Mutex};
1312

1413
use uany::UncheckedBoxAnyDowncast;
1514
use openssl::ssl::{SslStream, SslContext};
@@ -53,9 +52,9 @@ pub trait NetworkStream: Stream + Any + Clone + Send {
5352
}
5453

5554
/// A connector creates a NetworkStream.
56-
pub trait NetworkConnector: NetworkStream {
55+
pub trait NetworkConnector<T>: NetworkStream {
5756
/// Connect to a remote address.
58-
fn connect<To: ToSocketAddr>(addr: To, scheme: &str) -> IoResult<Self>;
57+
fn connect<To: ToSocketAddr, F: FnOnce() -> IoResult<T>>(addr: To, scheme: &str, t: F) -> IoResult<Self>;
5958
}
6059

6160
impl fmt::Show for Box<NetworkStream + Send> {
@@ -189,19 +188,15 @@ pub enum HttpStream {
189188
/// A stream over the HTTP protocol.
190189
Http(TcpStream),
191190
/// A stream over the HTTP protocol, protected by SSL.
192-
// You may be asking wtf an Arc and Mutex? That's because SslStream
193-
// doesn't implement Clone, and we need Clone to use the stream for
194-
// both the Request and Response.
195-
// FIXME: https://github.com/sfackler/rust-openssl/issues/6
196-
Https(Arc<Mutex<SslStream<TcpStream>>>, SocketAddr),
191+
Https(SslStream<TcpStream>),
197192
}
198193

199194
impl Reader for HttpStream {
200195
#[inline]
201196
fn read(&mut self, buf: &mut [u8]) -> IoResult<uint> {
202197
match *self {
203198
Http(ref mut inner) => inner.read(buf),
204-
Https(ref mut inner, _) => inner.lock().read(buf)
199+
Https(ref mut inner) => inner.read(buf)
205200
}
206201
}
207202
}
@@ -211,14 +206,14 @@ impl Writer for HttpStream {
211206
fn write(&mut self, msg: &[u8]) -> IoResult<()> {
212207
match *self {
213208
Http(ref mut inner) => inner.write(msg),
214-
Https(ref mut inner, _) => inner.lock().write(msg)
209+
Https(ref mut inner) => inner.write(msg)
215210
}
216211
}
217212
#[inline]
218213
fn flush(&mut self) -> IoResult<()> {
219214
match *self {
220215
Http(ref mut inner) => inner.flush(),
221-
Https(ref mut inner, _) => inner.lock().flush(),
216+
Https(ref mut inner) => inner.flush(),
222217
}
223218
}
224219
}
@@ -228,27 +223,25 @@ impl NetworkStream for HttpStream {
228223
fn peer_name(&mut self) -> IoResult<SocketAddr> {
229224
match *self {
230225
Http(ref mut inner) => inner.peer_name(),
231-
Https(_, addr) => Ok(addr)
226+
Https(ref mut inner) => inner.get_mut().peer_name()
232227
}
233228
}
234229
}
235230

236-
impl NetworkConnector for HttpStream {
237-
fn connect<To: ToSocketAddr>(addr: To, scheme: &str) -> IoResult<HttpStream> {
231+
232+
impl NetworkConnector<SslContext> for HttpStream {
233+
fn connect<To: ToSocketAddr, F: FnOnce() -> IoResult<SslContext>>(addr: To, scheme: &str, contexter: F) -> IoResult<HttpStream> {
238234
match scheme {
239235
"http" => {
240236
debug!("http scheme");
241237
Ok(Http(try!(TcpStream::connect(addr))))
242238
},
243239
"https" => {
244240
debug!("https scheme");
245-
let mut stream = try!(TcpStream::connect(addr));
246-
// we can't access the tcp stream once it's wrapped in an
247-
// SslStream, so grab the ip address now, just in case.
248-
let peer_addr = try!(stream.peer_name());
249-
let context = try!(SslContext::new(Sslv23).map_err(lift_ssl_error));
241+
let stream = try!(TcpStream::connect(addr));
242+
let context = try!(contexter());
250243
let stream = try!(SslStream::new(&context, stream).map_err(lift_ssl_error));
251-
Ok(Https(Arc::new(Mutex::new(stream)), peer_addr))
244+
Ok(Https(stream))
252245
},
253246
_ => {
254247
Err(IoError {
@@ -261,6 +254,16 @@ impl NetworkConnector for HttpStream {
261254
}
262255
}
263256

257+
impl HttpStream {
258+
#[doc(hidden)]
259+
#[inline]
260+
pub fn ssl_context() -> IoResult<SslContext> {
261+
SslContext::new(Sslv23).map_err(lift_ssl_error)
262+
}
263+
}
264+
265+
266+
264267
fn lift_ssl_error(ssl: SslError) -> IoError {
265268
match ssl {
266269
StreamError(err) => err,

0 commit comments

Comments
 (0)