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
pub use self::websocket::Message;
pub use self::websocket::SendError;
pub use self::websocket::Websocket;
use std::ascii::AsciiExt;
use std::borrow::Cow;
use std::error;
use std::fmt;
use std::sync::mpsc;
use std::vec::IntoIter as VecIntoIter;
use sha1::Sha1;
use rustc_serialize::base64::Config;
use rustc_serialize::base64::Standard;
use rustc_serialize::base64::Newline;
use rustc_serialize::base64::ToBase64;
use Request;
use Response;
mod low_level;
mod websocket;
#[derive(Debug)]
pub enum WebsocketError {
InvalidWebsocketRequest,
WrongSubprotocol,
}
impl error::Error for WebsocketError {
#[inline]
fn description(&self) -> &str {
match *self {
WebsocketError::InvalidWebsocketRequest => {
"the request does not match a websocket request"
},
WebsocketError::WrongSubprotocol => {
"the subprotocol passed to the function was not requested by the client"
},
}
}
}
impl fmt::Display for WebsocketError {
#[inline]
fn fmt(&self, fmt: &mut fmt::Formatter) -> Result<(), fmt::Error> {
write!(fmt, "{}", error::Error::description(self))
}
}
pub fn start<S>(request: &Request, subprotocol: Option<S>)
-> Result<(Response, mpsc::Receiver<Websocket>), WebsocketError>
where S: Into<Cow<'static, str>>
{
let subprotocol = subprotocol.map(|s| s.into());
if request.method() != "GET" {
return Err(WebsocketError::InvalidWebsocketRequest);
}
match request.header("Connection") {
Some(ref h) if h.to_ascii_lowercase().contains("upgrade") => (),
_ => return Err(WebsocketError::InvalidWebsocketRequest),
}
match request.header("Upgrade") {
Some(ref h) if h.to_ascii_lowercase().contains("websocket") => (),
_ => return Err(WebsocketError::InvalidWebsocketRequest),
}
match request.header("Sec-WebSocket-Version") {
Some(h) if h == "13" => (),
_ => return Err(WebsocketError::InvalidWebsocketRequest),
}
if let Some(ref sp) = subprotocol {
if !requested_protocols(request).any(|p| &p == sp) {
return Err(WebsocketError::WrongSubprotocol);
}
}
let key = {
let in_key = match request.header("Sec-WebSocket-Key") {
Some(h) => h,
None => return Err(WebsocketError::InvalidWebsocketRequest),
};
convert_key(&in_key)
};
let (tx, rx) = mpsc::channel();
let mut response = Response::text("");
response.status_code = 101;
response.headers.push(("Upgrade".into(), "websocket".into()));
if let Some(sp) = subprotocol {
response.headers.push(("Sec-Websocket-Protocol".into(), sp.into()));
}
response.headers.push(("Sec-Websocket-Accept".into(), key.into()));
response.upgrade = Some(Box::new(tx) as Box<_>);
Ok((response, rx))
}
pub fn requested_protocols(request: &Request) -> RequestedProtocolsIter {
match request.header("Sec-WebSocket-Protocol") {
None => RequestedProtocolsIter { iter: Vec::new().into_iter() },
Some(h) => {
let iter = h.split(',')
.map(|s| s.trim())
.filter(|s| !s.is_empty())
.map(|s| s.to_owned())
.collect::<Vec<_>>().into_iter();
RequestedProtocolsIter { iter: iter }
}
}
}
pub struct RequestedProtocolsIter {
iter: VecIntoIter<String>,
}
impl Iterator for RequestedProtocolsIter {
type Item = String;
#[inline]
fn next(&mut self) -> Option<String> {
self.iter.next()
}
#[inline]
fn size_hint(&self) -> (usize, Option<usize>) {
self.iter.size_hint()
}
}
impl ExactSizeIterator for RequestedProtocolsIter {
}
fn convert_key(input: &str) -> String {
let mut sha1 = Sha1::new();
sha1.update(input.as_bytes());
sha1.update(b"258EAFA5-E914-47DA-95CA-C5AB0DC85B11");
sha1.digest().bytes().to_base64(Config { char_set: Standard, pad: true,
line_length: None, newline: Newline::LF })
}