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
use std::borrow::Cow;
use std::error;
use std::fmt;
use std::io;
use std::io::Error as IoError;
use std::io::BufRead;
use std::io::Read;
use std::io::Write;
use std::net::TcpStream;
use std::net::ToSocketAddrs;
use Request;
use Response;
use ResponseBody;
#[derive(Debug)]
pub enum ProxyError {
BodyAlreadyExtracted,
IoError(IoError),
HttpParseError,
}
impl From<IoError> for ProxyError {
fn from(err: IoError) -> ProxyError {
ProxyError::IoError(err)
}
}
impl error::Error for ProxyError {
#[inline]
fn description(&self) -> &str {
match *self {
ProxyError::BodyAlreadyExtracted => {
"the body of the request was already extracted"
},
ProxyError::IoError(_) => {
"could not read the body from the request, or could not connect to the remote \
server, or the connection to the remote server closed unexpectedly"
},
ProxyError::HttpParseError => {
"the destination server didn't produce compliant HTTP"
},
}
}
#[inline]
fn cause(&self) -> Option<&error::Error> {
match *self {
ProxyError::IoError(ref e) => Some(e),
_ => None
}
}
}
impl fmt::Display for ProxyError {
#[inline]
fn fmt(&self, fmt: &mut fmt::Formatter) -> Result<(), fmt::Error> {
write!(fmt, "{}", error::Error::description(self))
}
}
#[derive(Debug, Clone)]
pub struct ProxyConfig<A> {
pub addr: A,
pub replace_host: Option<Cow<'static, str>>,
}
pub fn proxy<A>(request: &Request, config: ProxyConfig<A>) -> Result<Response, ProxyError>
where A: ToSocketAddrs
{
let mut socket = try!(TcpStream::connect(config.addr));
let mut data = match request.data() {
Some(d) => d,
None => return Err(ProxyError::BodyAlreadyExtracted),
};
try!(socket.write_all(format!("{} {} HTTP/1.1\n", request.method(), request.raw_url()).as_bytes()));
for &(ref header, ref value) in request.headers.iter() {
let value = if header == "Host" {
if let Some(ref replace) = config.replace_host {
&**replace
} else {
value
}
} else {
value
};
try!(socket.write_all(format!("{}: {}\n", header, value).as_bytes()));
}
try!(socket.write_all("Connection: close\n\n".as_bytes()));
try!(io::copy(&mut data, &mut socket));
let mut socket = io::BufReader::new(socket);
let mut headers = Vec::new();
let status;
{
let mut lines = socket.by_ref().lines();
{
let line = try!(match lines.next() {
Some(l) => l,
None => return Err(ProxyError::HttpParseError),
});
let mut splits = line.splitn(3, ' ');
let _ = splits.next();
let status_str = match splits.next() {
Some(l) => l,
None => return Err(ProxyError::HttpParseError),
};
status = match status_str.parse() {
Ok(s) => s,
Err(_) => return Err(ProxyError::HttpParseError),
};
}
for header in lines {
let header = try!(header);
if header.is_empty() { break; }
let mut splits = header.splitn(2, ':');
let header = match splits.next() {
Some(v) => v,
None => return Err(ProxyError::HttpParseError),
};
let val = match splits.next() {
Some(v) => v,
None => return Err(ProxyError::HttpParseError),
};
let val = &val[1..];
headers.push((header.to_owned().into(), val.to_owned().into()));
}
}
Ok(Response {
status_code: status,
headers: headers,
data: ResponseBody::from_reader(socket),
upgrade: None,
})
}