-
Notifications
You must be signed in to change notification settings - Fork 6
Expand file tree
/
Copy pathbridge.rs
More file actions
278 lines (238 loc) · 8.29 KB
/
Copy pathbridge.rs
File metadata and controls
278 lines (238 loc) · 8.29 KB
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
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
use std::convert::Infallible;
use std::future::Future;
use std::pin::Pin;
use std::sync::Arc;
use anyhow::Context;
use bytes::Bytes;
use http_body_util::combinators::BoxBody;
use http_body_util::{BodyExt, Empty, Full};
use hyper::body::Incoming;
use hyper::client::conn::http2 as h2_client;
use hyper::service::Service;
use hyper::{Method, Request, Response, StatusCode};
use hyper_util::rt::{TokioExecutor, TokioIo};
use rustls::ClientConfig;
use rustls_pki_types::ServerName;
use tokio::io::copy_bidirectional;
use tokio::net::TcpStream;
use tokio::sync::Mutex;
use tracing::{error, info, warn};
type Body = BoxBody<Bytes, Infallible>;
pub struct GatewayConnector {
tls_config: Arc<ClientConfig>,
sni: ServerName<'static>,
host: String,
port: u16,
sender: Mutex<Option<h2_client::SendRequest<Body>>>,
}
impl GatewayConnector {
pub fn new(
tls_config: Arc<ClientConfig>,
sni: ServerName<'static>,
host: String,
port: u16,
) -> Self {
Self {
tls_config,
sni,
host,
port,
sender: Mutex::new(None),
}
}
async fn connect_fresh(&self) -> anyhow::Result<h2_client::SendRequest<Body>> {
let tcp = TcpStream::connect((&*self.host, self.port))
.await
.with_context(|| format!("TCP connect to {}:{}", self.host, self.port))?;
let connector = tokio_rustls::TlsConnector::from(self.tls_config.clone());
let tls = connector
.connect(self.sni.clone(), tcp)
.await
.with_context(|| format!("TLS handshake with {}:{}", self.host, self.port))?;
let io = TokioIo::new(tls);
let (sender, conn) = h2_client::handshake(TokioExecutor::new(), io)
.await
.context("h2 handshake with gateway")?;
tokio::spawn(async move {
if let Err(e) = conn.await {
warn!(error = %e, "gateway h2 connection closed");
}
});
Ok(sender)
}
/// Return a live sender, connecting if needed. The lock is only held briefly
/// to read/write the cached sender — never across network I/O.
async fn get_sender(&self) -> anyhow::Result<h2_client::SendRequest<Body>> {
{
let guard = self.sender.lock().await;
if let Some(ref sender) = *guard
&& !sender.is_closed()
{
return Ok(sender.clone());
}
}
let sender = self.connect_fresh().await?;
{
let mut guard = self.sender.lock().await;
*guard = Some(sender.clone());
}
Ok(sender)
}
fn invalidate_sender(&self) {
if let Ok(mut guard) = self.sender.try_lock() {
*guard = None;
}
}
/// Send a CONNECT request to the gateway. On connection error, reconnect once and retry.
pub async fn send_connect(
&self,
authority: &str,
) -> anyhow::Result<Response<Incoming>> {
let req = build_connect_request(authority)?;
let mut sender = self.get_sender().await?;
match sender.send_request(req).await {
Ok(resp) => Ok(resp),
Err(first_err) => {
warn!(error = %first_err, "gateway request failed, reconnecting");
self.invalidate_sender();
let retry_req = build_connect_request(authority)?;
let mut new_sender = self.get_sender().await?;
new_sender
.send_request(retry_req)
.await
.map_err(|e| anyhow::anyhow!("gateway retry failed: {e}"))
}
}
}
}
fn build_connect_request(authority: &str) -> anyhow::Result<Request<Body>> {
let uri = http::Uri::builder()
.authority(authority)
.build()
.context("building CONNECT URI")?;
let req = Request::builder()
.method(Method::CONNECT)
.uri(uri)
.body(Empty::<Bytes>::new().boxed())
.context("building CONNECT request")?;
Ok(req)
}
#[derive(Clone)]
struct SidecarService {
connector: Arc<GatewayConnector>,
}
impl Service<Request<Incoming>> for SidecarService {
type Response = Response<Body>;
type Error = Infallible;
type Future = Pin<Box<dyn Future<Output = Result<Self::Response, Self::Error>> + Send>>;
fn call(&self, req: Request<Incoming>) -> Self::Future {
let connector = self.connector.clone();
Box::pin(async move { Ok(handle(req, connector).await) })
}
}
async fn handle(req: Request<Incoming>, connector: Arc<GatewayConnector>) -> Response<Body> {
if req.method() != Method::CONNECT {
return response(StatusCode::METHOD_NOT_ALLOWED, "only CONNECT is supported");
}
let authority = match req.uri().authority() {
Some(a) => a.to_string(),
None => return response(StatusCode::BAD_REQUEST, "missing authority"),
};
info!(dest = %authority, "CONNECT request");
let gw_response = match connector.send_connect(&authority).await {
Ok(r) => r,
Err(e) => {
error!(dest = %authority, error = %e, "gateway connect failed");
return response(StatusCode::BAD_GATEWAY, "gateway unreachable");
}
};
let status = gw_response.status();
if status != StatusCode::OK {
warn!(dest = %authority, %status, "gateway rejected CONNECT");
return response(status, "gateway denied request");
}
let gw_upgraded = match hyper::upgrade::on(gw_response).await {
Ok(u) => u,
Err(e) => {
error!(dest = %authority, error = %e, "gateway upgrade failed");
return response(StatusCode::BAD_GATEWAY, "gateway tunnel failed");
}
};
let client_upgrade = hyper::upgrade::on(req);
tokio::spawn(async move {
let client_upgraded = match client_upgrade.await {
Ok(u) => u,
Err(e) => {
warn!(dest = %authority, error = %e, "client upgrade failed");
return;
}
};
let mut client_io = TokioIo::new(client_upgraded);
let mut gw_io = TokioIo::new(gw_upgraded);
match copy_bidirectional(&mut client_io, &mut gw_io).await {
Ok((up, down)) => {
info!(
dest = %authority,
client_to_dest = up,
dest_to_client = down,
"tunnel closed"
);
}
Err(e) => {
error!(dest = %authority, error = %e, "tunnel error");
}
}
});
response(StatusCode::OK, "")
}
fn response(status: StatusCode, message: &str) -> Response<Body> {
let body: Body = if message.is_empty() {
Empty::<Bytes>::new().boxed()
} else {
Full::new(Bytes::from(message.to_owned())).boxed()
};
let mut resp = Response::new(body);
*resp.status_mut() = status;
resp
}
pub async fn serve_connection(
stream: TcpStream,
connector: Arc<GatewayConnector>,
) -> anyhow::Result<()> {
let service = SidecarService { connector };
let io = TokioIo::new(stream);
hyper_util::server::conn::auto::Builder::new(TokioExecutor::new())
.serve_connection_with_upgrades(io, service)
.await
.map_err(|e| anyhow::anyhow!("serve error: {e}"))
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn connect_request_has_correct_method_and_authority() {
let req = build_connect_request("example.com:443").unwrap();
assert_eq!(req.method(), Method::CONNECT);
assert_eq!(req.uri().authority().unwrap().as_str(), "example.com:443");
}
#[test]
fn connect_request_ipv6() {
let req = build_connect_request("[::1]:8443").unwrap();
assert_eq!(req.uri().authority().unwrap().as_str(), "[::1]:8443");
}
#[test]
fn response_ok_has_empty_body() {
let resp = response(StatusCode::OK, "");
assert_eq!(resp.status(), StatusCode::OK);
}
#[test]
fn response_error_has_status_and_body() {
let resp = response(StatusCode::FORBIDDEN, "denied");
assert_eq!(resp.status(), StatusCode::FORBIDDEN);
}
#[test]
fn response_bad_gateway() {
let resp = response(StatusCode::BAD_GATEWAY, "gateway unreachable");
assert_eq!(resp.status(), StatusCode::BAD_GATEWAY);
}
}