-
Notifications
You must be signed in to change notification settings - Fork 64
/
Copy pathlib.rs
387 lines (314 loc) · 11.5 KB
/
lib.rs
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
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
#![doc = include_str!("../README.md")]
#[macro_use]
extern crate tracing;
use hyper::header::{HeaderMap, HeaderName, HeaderValue, HOST};
use hyper::http::header::{InvalidHeaderValue, ToStrError};
use hyper::http::uri::InvalidUri;
use hyper::upgrade::OnUpgrade;
use hyper::{Body, Client, Error, Request, Response, StatusCode};
use lazy_static::lazy_static;
use std::net::IpAddr;
use tokio::io::copy_bidirectional;
lazy_static! {
static ref TE_HEADER: HeaderName = HeaderName::from_static("te");
static ref CONNECTION_HEADER: HeaderName = HeaderName::from_static("connection");
static ref UPGRADE_HEADER: HeaderName = HeaderName::from_static("upgrade");
static ref TRAILER_HEADER: HeaderName = HeaderName::from_static("trailer");
static ref TRAILERS_HEADER: HeaderName = HeaderName::from_static("trailers");
// A list of the headers, using hypers actual HeaderName comparison
static ref HOP_HEADERS: [HeaderName; 9] = [
CONNECTION_HEADER.clone(),
TE_HEADER.clone(),
TRAILER_HEADER.clone(),
HeaderName::from_static("keep-alive"),
HeaderName::from_static("proxy-connection"),
HeaderName::from_static("proxy-authenticate"),
HeaderName::from_static("proxy-authorization"),
HeaderName::from_static("transfer-encoding"),
HeaderName::from_static("upgrade"),
];
static ref X_FORWARDED_FOR: HeaderName = HeaderName::from_static("x-forwarded-for");
}
#[derive(Debug)]
pub enum ProxyError {
InvalidUri(InvalidUri),
HyperError(Error),
ForwardHeaderError,
UpgradeError(String),
}
impl From<Error> for ProxyError {
fn from(err: Error) -> ProxyError {
ProxyError::HyperError(err)
}
}
impl From<InvalidUri> for ProxyError {
fn from(err: InvalidUri) -> ProxyError {
ProxyError::InvalidUri(err)
}
}
impl From<ToStrError> for ProxyError {
fn from(_err: ToStrError) -> ProxyError {
ProxyError::ForwardHeaderError
}
}
impl From<InvalidHeaderValue> for ProxyError {
fn from(_err: InvalidHeaderValue) -> ProxyError {
ProxyError::ForwardHeaderError
}
}
fn remove_hop_headers(headers: &mut HeaderMap) {
debug!("Removing hop headers");
for header in &*HOP_HEADERS {
headers.remove(header);
}
}
fn get_upgrade_type(headers: &HeaderMap) -> Option<String> {
#[allow(clippy::blocks_in_if_conditions)]
if headers
.get(&*CONNECTION_HEADER)
.map(|value| {
value
.to_str()
.unwrap()
.split(',')
.any(|e| e.trim() == *UPGRADE_HEADER)
})
.unwrap_or(false)
{
if let Some(upgrade_value) = headers.get(&*UPGRADE_HEADER) {
debug!(
"Found upgrade header with value: {}",
upgrade_value.to_str().unwrap().to_owned()
);
return Some(upgrade_value.to_str().unwrap().to_owned());
}
}
None
}
fn remove_connection_headers(headers: &mut HeaderMap) {
if headers.get(&*CONNECTION_HEADER).is_some() {
debug!("Removing connection headers");
let value = headers.get(&*CONNECTION_HEADER).cloned().unwrap();
for name in value.to_str().unwrap().split(',') {
if !name.trim().is_empty() {
headers.remove(name.trim());
}
}
}
}
fn create_proxied_response<B>(mut response: Response<B>) -> Response<B> {
info!("Creating proxied response");
remove_hop_headers(response.headers_mut());
remove_connection_headers(response.headers_mut());
response
}
fn forward_uri<B>(forward_url: &str, req: &Request<B>) -> String {
debug!("Building forward uri");
let split_url = forward_url.split('?').collect::<Vec<&str>>();
let mut base_url: &str = split_url.get(0).unwrap_or(&"");
let forward_url_query: &str = split_url.get(1).unwrap_or(&"");
let path2 = req.uri().path();
if base_url.ends_with('/') {
let mut path1_chars = base_url.chars();
path1_chars.next_back();
base_url = path1_chars.as_str();
}
let total_length = base_url.len()
+ path2.len()
+ 1
+ forward_url_query.len()
+ req.uri().query().map(|e| e.len()).unwrap_or(0);
debug!("Creating url with capacity to {}", total_length);
let mut url = String::with_capacity(total_length);
url.push_str(base_url);
url.push_str(path2);
if !forward_url_query.is_empty() || req.uri().query().map(|e| !e.is_empty()).unwrap_or(false) {
debug!("Adding query parts to url");
url.push('?');
url.push_str(forward_url_query);
if forward_url_query.is_empty() {
debug!("Using request query");
url.push_str(req.uri().query().unwrap_or(""));
} else {
debug!("Merging request and forward_url query");
let request_query_items = req.uri().query().unwrap_or("").split('&').map(|el| {
let parts = el.split('=').collect::<Vec<&str>>();
(parts[0], if parts.len() > 1 { parts[1] } else { "" })
});
let forward_query_items = forward_url_query
.split('&')
.map(|el| {
let parts = el.split('=').collect::<Vec<&str>>();
parts[0]
})
.collect::<Vec<_>>();
for (key, value) in request_query_items {
if !forward_query_items.iter().any(|e| e == &key) {
url.push('&');
url.push_str(key);
url.push('=');
url.push_str(value);
}
}
if url.ends_with('&') {
let mut parts = url.chars();
parts.next_back();
url = parts.as_str().to_string();
}
}
}
debug!("Built forwarding url from request: {}", url);
url.parse().unwrap()
}
fn create_proxied_request<B>(
client_ip: IpAddr,
forward_url: &str,
mut request: Request<B>,
upgrade_type: Option<&String>,
) -> Result<Request<B>, ProxyError> {
info!("Creating proxied request");
let contains_te_trailers_value = request
.headers()
.get(&*TE_HEADER)
.map(|value| {
value
.to_str()
.unwrap()
.split(',')
.any(|e| e.trim() == *TRAILERS_HEADER)
})
.unwrap_or(false);
let uri: hyper::Uri = forward_uri(forward_url, &request).parse()?;
debug!("Setting headers of proxied request");
// remove the original HOST header. It will be set by the client that sends the request
request.headers_mut().remove(HOST);
*request.uri_mut() = uri;
remove_hop_headers(request.headers_mut());
remove_connection_headers(request.headers_mut());
if contains_te_trailers_value {
debug!("Setting up trailer headers");
request
.headers_mut()
.insert(&*TE_HEADER, HeaderValue::from_static("trailers"));
}
if let Some(value) = upgrade_type {
debug!("Repopulate upgrade headers");
request
.headers_mut()
.insert(&*UPGRADE_HEADER, value.parse().unwrap());
request
.headers_mut()
.insert(&*CONNECTION_HEADER, HeaderValue::from_static("UPGRADE"));
}
// Add forwarding information in the headers
match request.headers_mut().entry(&*X_FORWARDED_FOR) {
hyper::header::Entry::Vacant(entry) => {
debug!("X-Fowraded-for header was vacant");
entry.insert(client_ip.to_string().parse()?);
}
hyper::header::Entry::Occupied(entry) => {
debug!("X-Fowraded-for header was occupied");
let client_ip_str = client_ip.to_string();
let mut addr =
String::with_capacity(entry.get().as_bytes().len() + 2 + client_ip_str.len());
addr.push_str(std::str::from_utf8(entry.get().as_bytes()).unwrap());
addr.push(',');
addr.push(' ');
addr.push_str(&client_ip_str);
}
}
debug!("Created proxied request");
Ok(request)
}
pub async fn call<'a, T: hyper::client::connect::Connect + Clone + Send + Sync + 'static>(
client_ip: IpAddr,
forward_uri: &str,
mut request: Request<Body>,
client: &'a Client<T>,
) -> Result<Response<Body>, ProxyError> {
info!(
"Received proxy call from {} to {}, client: {}",
request.uri().to_string(),
forward_uri,
client_ip
);
let request_upgrade_type = get_upgrade_type(request.headers());
let request_upgraded = request.extensions_mut().remove::<OnUpgrade>();
let proxied_request = create_proxied_request(
client_ip,
forward_uri,
request,
request_upgrade_type.as_ref(),
)?;
let mut response = client.request(proxied_request).await?;
if response.status() == StatusCode::SWITCHING_PROTOCOLS {
let response_upgrade_type = get_upgrade_type(response.headers());
if request_upgrade_type == response_upgrade_type {
if let Some(request_upgraded) = request_upgraded {
let mut response_upgraded = response
.extensions_mut()
.remove::<OnUpgrade>()
.expect("response does not have an upgrade extension")
.await?;
debug!("Responding to a connection upgrade response");
tokio::spawn(async move {
let mut request_upgraded =
request_upgraded.await.expect("failed to upgrade request");
copy_bidirectional(&mut response_upgraded, &mut request_upgraded)
.await
.expect("coping between upgraded connections failed");
});
Ok(response)
} else {
Err(ProxyError::UpgradeError(
"request does not have an upgrade extension".to_string(),
))
}
} else {
Err(ProxyError::UpgradeError(format!(
"backend tried to switch to protocol {:?} when {:?} was requested",
response_upgrade_type, request_upgrade_type
)))
}
} else {
let proxied_response = create_proxied_response(response);
debug!("Responding to call with response");
Ok(proxied_response)
}
}
pub struct ReverseProxy<T: hyper::client::connect::Connect + Clone + Send + Sync + 'static> {
client: Client<T>,
}
impl<T: hyper::client::connect::Connect + Clone + Send + Sync + 'static> ReverseProxy<T> {
pub fn new(client: Client<T>) -> Self {
Self { client }
}
pub async fn call(
&self,
client_ip: IpAddr,
forward_uri: &str,
request: Request<Body>,
) -> Result<Response<Body>, ProxyError> {
call::<T>(client_ip, forward_uri, request, &self.client).await
}
}
#[cfg(feature = "__bench")]
pub mod benches {
pub fn hop_headers() -> &'static [crate::HeaderName] {
&*super::HOP_HEADERS
}
pub fn create_proxied_response<T>(response: crate::Response<T>) {
super::create_proxied_response(response);
}
pub fn forward_uri<B>(forward_url: &str, req: &crate::Request<B>) {
super::forward_uri(forward_url, req);
}
pub fn create_proxied_request<B>(
client_ip: crate::IpAddr,
forward_url: &str,
request: crate::Request<B>,
upgrade_type: Option<&String>,
) {
super::create_proxied_request(client_ip, forward_url, request, upgrade_type).unwrap();
}
}