1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
#![deny(missing_docs)]
#![doc(html_root_url = "https://docs.rs/lapin-futures-rustls/0.16.0/")]
extern crate bytes;
extern crate futures;
extern crate lapin_futures;
extern crate tokio_executor;
extern crate tokio_io;
extern crate tokio_tcp;
extern crate tokio_rustls;
extern crate trust_dns_resolver;
extern crate webpki_roots;
pub mod lapin;
pub mod uri;
use tokio_rustls::{rustls, webpki};
use std::io::{self, Read, Write};
use std::net::SocketAddr;
use std::sync::Arc;
use bytes::{Buf, BufMut};
use futures::future::Future;
use futures::Poll;
use rustls::{ClientConfig, ClientSession};
use tokio_io::{AsyncRead, AsyncWrite};
use tokio_rustls::{TlsConnector, TlsStream};
use tokio_tcp::TcpStream;
use trust_dns_resolver::ResolverFuture;
use lapin::client::ConnectionOptions;
use uri::{AMQPScheme, AMQPUri};
pub enum AMQPStream {
Raw(TcpStream),
Tls(Box<TlsStream<TcpStream, ClientSession>>),
}
pub trait AMQPConnectionRustlsExt<F: FnOnce(io::Error) + Send + 'static> {
fn connect(self, heartbeat_error_handler: F) -> Box<Future<Item = lapin::client::Client<AMQPStream>, Error = io::Error> + Send + 'static>;
fn connect_cancellable(self, heartbeat_error_handler: F) -> Box<Future<Item = (lapin::client::Client<AMQPStream>, lapin::client::HeartbeatHandle), Error = io::Error> + Send + 'static>;
}
impl<F: FnOnce(io::Error) + Send + 'static> AMQPConnectionRustlsExt<F> for AMQPUri {
fn connect(self, heartbeat_error_handler: F) -> Box<Future<Item = lapin::client::Client<AMQPStream>, Error = io::Error> + Send + 'static> {
Box::new(AMQPStream::from_amqp_uri(&self).and_then(move |stream| connect_stream(stream, self, heartbeat_error_handler, false)).map(|(client, _)| client))
}
fn connect_cancellable(self, heartbeat_error_handler: F) -> Box<Future<Item = (lapin::client::Client<AMQPStream>, lapin::client::HeartbeatHandle), Error = io::Error> + Send + 'static> {
Box::new(AMQPStream::from_amqp_uri(&self).and_then(move |stream| connect_stream(stream, self, heartbeat_error_handler, true)).map(|(client, heartbeat_handle)| (client, heartbeat_handle.unwrap())))
}
}
impl<'a, F: FnOnce(io::Error) + Send + 'static> AMQPConnectionRustlsExt<F> for &'a str {
fn connect(self, heartbeat_error_handler: F) -> Box<Future<Item = lapin::client::Client<AMQPStream>, Error = io::Error> + Send + 'static> {
match self.parse::<AMQPUri>() {
Ok(uri) => uri.connect(heartbeat_error_handler),
Err(err) => Box::new(futures::future::err(io::Error::new(io::ErrorKind::Other, err))),
}
}
fn connect_cancellable(self, heartbeat_error_handler: F) -> Box<Future<Item = (lapin::client::Client<AMQPStream>, lapin::client::HeartbeatHandle), Error = io::Error> + Send + 'static> {
match self.parse::<AMQPUri>() {
Ok(uri) => uri.connect_cancellable(heartbeat_error_handler),
Err(err) => Box::new(futures::future::err(io::Error::new(io::ErrorKind::Other, err))),
}
}
}
impl AMQPStream {
fn from_amqp_uri(uri: &AMQPUri) -> Box<Future<Item = Self, Error = io::Error> + Send + 'static> {
match uri.scheme {
AMQPScheme::AMQP => AMQPStream::raw(uri.authority.host.clone(), uri.authority.port),
AMQPScheme::AMQPS => AMQPStream::tls(uri.authority.host.clone(), uri.authority.port),
}
}
fn raw(host: String, port: u16) -> Box<Future<Item = Self, Error = io::Error> + Send + 'static> {
Box::new(open_tcp_stream(host, port).map(AMQPStream::Raw))
}
fn tls(host: String, port: u16) -> Box<Future<Item = Self, Error = io::Error> + Send + 'static> {
let mut config = ClientConfig::new();
config.root_store.add_server_trust_anchors(&webpki_roots::TLS_SERVER_ROOTS);
let config = TlsConnector::from(Arc::new(config));
Box::new(
open_tcp_stream(host.clone(), port).join(
futures::future::result(webpki::DNSNameRef::try_from_ascii_str(&host).map(move |domain| domain.to_owned()).map_err(|()| io::Error::new(io::ErrorKind::Other, "Invalid domain name")))
).and_then(move |(stream, domain)| {
config.connect(domain.as_ref(), stream).map_err(From::from).map(Box::new).map(AMQPStream::Tls)
})
)
}
}
impl Read for AMQPStream {
fn read(&mut self, buf: &mut [u8]) -> io::Result<usize> {
match *self {
AMQPStream::Raw(ref mut raw) => raw.read(buf),
AMQPStream::Tls(ref mut tls) => tls.read(buf),
}
}
}
impl AsyncRead for AMQPStream {
unsafe fn prepare_uninitialized_buffer(&self, buf: &mut [u8]) -> bool {
match *self {
AMQPStream::Raw(ref raw) => raw.prepare_uninitialized_buffer(buf),
AMQPStream::Tls(ref tls) => tls.prepare_uninitialized_buffer(buf),
}
}
fn read_buf<B: BufMut>(&mut self, buf: &mut B) -> Poll<usize, io::Error> {
match *self {
AMQPStream::Raw(ref mut raw) => raw.read_buf(buf),
AMQPStream::Tls(ref mut tls) => tls.read_buf(buf),
}
}
}
impl Write for AMQPStream {
fn write(&mut self, buf: &[u8]) -> io::Result<usize> {
match *self {
AMQPStream::Raw(ref mut raw) => raw.write(buf),
AMQPStream::Tls(ref mut tls) => tls.write(buf),
}
}
fn flush(&mut self) -> io::Result<()> {
match *self {
AMQPStream::Raw(ref mut raw) => raw.flush(),
AMQPStream::Tls(ref mut tls) => tls.flush(),
}
}
}
impl AsyncWrite for AMQPStream {
fn shutdown(&mut self) -> Poll<(), io::Error> {
match *self {
AMQPStream::Raw(ref mut raw) => raw.shutdown(),
AMQPStream::Tls(ref mut tls) => tls.shutdown(),
}
}
fn write_buf<B: Buf>(&mut self, buf: &mut B) -> Poll<usize, io::Error> {
match *self {
AMQPStream::Raw(ref mut raw) => raw.write_buf(buf),
AMQPStream::Tls(ref mut tls) => tls.write_buf(buf),
}
}
}
fn open_tcp_stream(host: String, port: u16) -> Box<Future<Item = TcpStream, Error = io::Error> + Send + 'static> {
let host = host.clone();
Box::new(
futures::future::result(ResolverFuture::from_system_conf()).flatten().and_then(move |resolver| {
resolver.lookup_ip(host.as_str())
}).map_err(From::from).and_then(|response| {
response.iter().next().ok_or_else(|| io::Error::new(io::ErrorKind::AddrNotAvailable, "Couldn't resolve hostname"))
}).and_then(move |ipaddr| {
TcpStream::connect(&SocketAddr::new(ipaddr, port))
})
)
}
fn connect_stream<T: AsyncRead + AsyncWrite + Send + Sync + 'static, F: FnOnce(io::Error) + Send + 'static>(stream: T, uri: AMQPUri, heartbeat_error_handler: F, create_heartbeat_handle: bool) -> Box<Future<Item = (lapin::client::Client<T>, Option<lapin::client::HeartbeatHandle>), Error = io::Error> + Send + 'static> {
Box::new(lapin::client::Client::connect(stream, ConnectionOptions::from_uri(uri)).map(move |(client, mut heartbeat_future)| {
let heartbeat_handle = if create_heartbeat_handle { heartbeat_future.handle() } else { None };
tokio_executor::spawn(heartbeat_future.map_err(heartbeat_error_handler));
(client, heartbeat_handle)
}))
}