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
use std::borrow::Cow;
use std::io::{Read, Write};
use std::marker::PhantomData;
use base64;
use httparse::Status;
use httparse;
use rand;
use url::Url;
use error::{Error, Result};
use protocol::{WebSocket, WebSocketConfig, Role};
use super::headers::{Headers, FromHttparse, MAX_HEADERS};
use super::machine::{HandshakeMachine, StageResult, TryParse};
use super::{MidHandshake, HandshakeRole, ProcessingResult, convert_key};
#[derive(Debug)]
pub struct Request<'t> {
pub url: Url,
pub extra_headers: Option<Vec<(Cow<'t, str>, Cow<'t, str>)>>,
}
impl<'t> Request<'t> {
fn get_path(&self) -> String {
if let Some(query) = self.url.query() {
format!("{path}?{query}", path = self.url.path(), query = query)
} else {
self.url.path().into()
}
}
fn get_host(&self) -> String {
let host = self.url.host_str().expect("Bug: URL without host");
if let Some(port) = self.url.port() {
format!("{host}:{port}", host = host, port = port)
} else {
host.into()
}
}
pub fn add_protocol(&mut self, protocol: Cow<'t, str>) {
self.add_header(Cow::from("Sec-WebSocket-Protocol"), protocol);
}
pub fn add_header(&mut self, name: Cow<'t, str>, value: Cow<'t, str>) {
let mut headers = self.extra_headers.take().unwrap_or_else(Vec::new);
headers.push((name, value));
self.extra_headers = Some(headers);
}
}
impl From<Url> for Request<'static> {
fn from(value: Url) -> Self {
Request {
url: value,
extra_headers: None,
}
}
}
#[derive(Debug)]
pub struct ClientHandshake<S> {
verify_data: VerifyData,
config: Option<WebSocketConfig>,
_marker: PhantomData<S>,
}
impl<S: Read + Write> ClientHandshake<S> {
pub fn start(
stream: S,
request: Request,
config: Option<WebSocketConfig>
) -> MidHandshake<Self> {
let key = generate_key();
let machine = {
let mut req = Vec::new();
write!(req, "\
GET {path} HTTP/1.1\r\n\
Host: {host}\r\n\
Connection: upgrade\r\n\
Upgrade: websocket\r\n\
Sec-WebSocket-Version: 13\r\n\
Sec-WebSocket-Key: {key}\r\n",
host = request.get_host(), path = request.get_path(), key = key).unwrap();
if let Some(eh) = request.extra_headers {
for (k, v) in eh {
write!(req, "{}: {}\r\n", k, v).unwrap();
}
}
write!(req, "\r\n").unwrap();
HandshakeMachine::start_write(stream, req)
};
let client = {
let accept_key = convert_key(key.as_ref()).unwrap();
ClientHandshake {
verify_data: VerifyData { accept_key },
config,
_marker: PhantomData,
}
};
trace!("Client handshake initiated.");
MidHandshake { role: client, machine }
}
}
impl<S: Read + Write> HandshakeRole for ClientHandshake<S> {
type IncomingData = Response;
type InternalStream = S;
type FinalResult = (WebSocket<S>, Response);
fn stage_finished(&mut self, finish: StageResult<Self::IncomingData, Self::InternalStream>)
-> Result<ProcessingResult<Self::InternalStream, Self::FinalResult>>
{
Ok(match finish {
StageResult::DoneWriting(stream) => {
ProcessingResult::Continue(HandshakeMachine::start_read(stream))
}
StageResult::DoneReading { stream, result, tail, } => {
self.verify_data.verify_response(&result)?;
debug!("Client handshake done.");
let websocket = WebSocket::from_partially_read(
stream,
tail,
Role::Client,
self.config.clone(),
);
ProcessingResult::Done((websocket, result))
}
})
}
}
#[derive(Debug)]
struct VerifyData {
accept_key: String,
}
impl VerifyData {
pub fn verify_response(&self, response: &Response) -> Result<()> {
if response.code != 101 {
return Err(Error::Http(response.code));
}
if !response.headers.header_is_ignore_case("Upgrade", "websocket") {
return Err(Error::Protocol("No \"Upgrade: websocket\" in server reply".into()));
}
if !response.headers.header_is_ignore_case("Connection", "Upgrade") {
return Err(Error::Protocol("No \"Connection: upgrade\" in server reply".into()));
}
if !response.headers.header_is("Sec-WebSocket-Accept", &self.accept_key) {
return Err(Error::Protocol("Key mismatch in Sec-WebSocket-Accept".into()));
}
Ok(())
}
}
#[derive(Debug)]
pub struct Response {
pub code: u16,
pub headers: Headers,
}
impl TryParse for Response {
fn try_parse(buf: &[u8]) -> Result<Option<(usize, Self)>> {
let mut hbuffer = [httparse::EMPTY_HEADER; MAX_HEADERS];
let mut req = httparse::Response::new(&mut hbuffer);
Ok(match req.parse(buf)? {
Status::Partial => None,
Status::Complete(size) => Some((size, Response::from_httparse(req)?)),
})
}
}
impl<'h, 'b: 'h> FromHttparse<httparse::Response<'h, 'b>> for Response {
fn from_httparse(raw: httparse::Response<'h, 'b>) -> Result<Self> {
if raw.version.expect("Bug: no HTTP version") < 1 {
return Err(Error::Protocol("HTTP version should be 1.1 or higher".into()));
}
Ok(Response {
code: raw.code.expect("Bug: no HTTP response code"),
headers: Headers::from_httparse(raw.headers)?,
})
}
}
fn generate_key() -> String {
let r: [u8; 16] = rand::random();
base64::encode(&r)
}
#[cfg(test)]
mod tests {
use super::{Response, generate_key};
use super::super::machine::TryParse;
#[test]
fn random_keys() {
let k1 = generate_key();
println!("Generated random key 1: {}", k1);
let k2 = generate_key();
println!("Generated random key 2: {}", k2);
assert_ne!(k1, k2);
assert_eq!(k1.len(), k2.len());
assert_eq!(k1.len(), 24);
assert_eq!(k2.len(), 24);
assert!(k1.ends_with("=="));
assert!(k2.ends_with("=="));
assert!(k1[..22].find("=").is_none());
assert!(k2[..22].find("=").is_none());
}
#[test]
fn response_parsing() {
const DATA: &'static [u8] = b"HTTP/1.1 200 OK\r\nContent-Type: text/html\r\n\r\n";
let (_, resp) = Response::try_parse(DATA).unwrap().unwrap();
assert_eq!(resp.code, 200);
assert_eq!(resp.headers.find_first("Content-Type"), Some(&b"text/html"[..]));
}
}