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
use bytes::{Buf, BytesMut};
use crate::{Parsing, extension::Extension};
use crate::connection::{self, Mode};
use futures::prelude::*;
use sha1::{Digest, Sha1};
use std::{mem, str};
use super::{
Error,
KEY,
MAX_NUM_HEADERS,
SEC_WEBSOCKET_EXTENSIONS,
SEC_WEBSOCKET_PROTOCOL,
append_extensions,
configure_extensions,
expect_ascii_header,
with_first_header
};
const BLOCK_SIZE: usize = 8 * 1024;
const SOKETTO_VERSION: &str = env!("CARGO_PKG_VERSION");
#[derive(Debug)]
pub struct Server<'a, T> {
socket: T,
protocols: Vec<&'a str>,
extensions: Vec<Box<dyn Extension + Send>>,
buffer: BytesMut
}
impl<'a, T: AsyncRead + AsyncWrite + Unpin> Server<'a, T> {
pub fn new(socket: T) -> Self {
Server {
socket,
protocols: Vec::new(),
extensions: Vec::new(),
buffer: BytesMut::new()
}
}
pub fn set_buffer(&mut self, b: BytesMut) -> &mut Self {
self.buffer = b;
self
}
pub fn take_buffer(&mut self) -> BytesMut {
mem::take(&mut self.buffer)
}
pub fn add_protocol(&mut self, p: &'a str) -> &mut Self {
self.protocols.push(p);
self
}
pub fn add_extension(&mut self, e: Box<dyn Extension + Send>) -> &mut Self {
self.extensions.push(e);
self
}
pub fn drain_extensions(&mut self) -> impl Iterator<Item = Box<dyn Extension + Send>> + '_ {
self.extensions.drain(..)
}
pub async fn receive_request(&mut self) -> Result<ClientRequest<'a>, Error> {
self.buffer.clear();
loop {
crate::read(&mut self.socket, &mut self.buffer, BLOCK_SIZE).await?;
if let Parsing::Done { value, offset } = self.decode_request()? {
self.buffer.advance(offset);
return Ok(value)
}
}
}
pub async fn send_response(&mut self, r: &Response<'_>) -> Result<(), Error> {
self.buffer.clear();
self.encode_response(r);
self.socket.write_all(&self.buffer).await?;
self.socket.flush().await?;
self.buffer.clear();
Ok(())
}
pub fn into_builder(mut self) -> connection::Builder<T> {
let mut builder = connection::Builder::new(self.socket, Mode::Server);
builder.set_buffer(self.buffer);
builder.add_extensions(self.extensions.drain(..));
builder
}
pub fn into_inner(self) -> T {
self.socket
}
fn decode_request(&mut self) -> Result<Parsing<ClientRequest<'a>>, Error> {
let mut header_buf = [httparse::EMPTY_HEADER; MAX_NUM_HEADERS];
let mut request = httparse::Request::new(&mut header_buf);
let offset = match request.parse(self.buffer.as_ref()) {
Ok(httparse::Status::Complete(off)) => off,
Ok(httparse::Status::Partial) => return Ok(Parsing::NeedMore(())),
Err(e) => return Err(Error::Http(Box::new(e)))
};
if request.method != Some("GET") {
return Err(Error::InvalidRequestMethod)
}
if request.version != Some(1) {
return Err(Error::UnsupportedHttpVersion)
}
with_first_header(&request.headers, "Host", |_h| Ok(()))?;
expect_ascii_header(request.headers, "Upgrade", "websocket")?;
expect_ascii_header(request.headers, "Connection", "upgrade")?;
expect_ascii_header(request.headers, "Sec-WebSocket-Version", "13")?;
let ws_key = with_first_header(&request.headers, "Sec-WebSocket-Key", |k| {
Ok(Vec::from(k))
})?;
for h in request.headers.iter()
.filter(|h| h.name.eq_ignore_ascii_case(SEC_WEBSOCKET_EXTENSIONS))
{
configure_extensions(&mut self.extensions, std::str::from_utf8(h.value)?)?
}
let mut protocols = Vec::new();
for p in request.headers.iter()
.filter(|h| h.name.eq_ignore_ascii_case(SEC_WEBSOCKET_PROTOCOL))
{
if let Some(&p) = self.protocols.iter().find(|x| x.as_bytes() == p.value) {
protocols.push(p)
}
}
let mut path = String::new();
if let Some(val) = request.path {
path.push_str(val)
}
Ok(Parsing::Done {
value: ClientRequest { ws_key, protocols, path }, offset,
})
}
fn encode_response(&mut self, response: &Response<'_>) {
match response {
Response::Accept { key, protocol } => {
let mut key_buf = [0; 32];
let accept_value = {
let mut digest = Sha1::new();
digest.update(key);
digest.update(KEY);
let d = digest.finalize();
let n = base64::encode_config_slice(&d, base64::STANDARD, &mut key_buf);
&key_buf[.. n]
};
self.buffer.extend_from_slice(b"HTTP/1.1 101 Switching Protocols");
self.buffer.extend_from_slice(b"\r\nServer: soketto-");
self.buffer.extend_from_slice(SOKETTO_VERSION.as_bytes());
self.buffer.extend_from_slice(b"\r\nUpgrade: websocket\r\nConnection: upgrade");
self.buffer.extend_from_slice(b"\r\nSec-WebSocket-Accept: ");
self.buffer.extend_from_slice(accept_value);
if let Some(p) = protocol {
self.buffer.extend_from_slice(b"\r\nSec-WebSocket-Protocol: ");
self.buffer.extend_from_slice(p.as_bytes())
}
append_extensions(self.extensions.iter().filter(|e| e.is_enabled()), &mut self.buffer);
self.buffer.extend_from_slice(b"\r\n\r\n")
}
Response::Reject { status_code } => {
self.buffer.extend_from_slice(b"HTTP/1.1 ");
let (_, s, reason) =
if let Ok(i) = STATUSCODES.binary_search_by_key(status_code, |(n, _, _)| *n) {
STATUSCODES[i]
} else {
(500, "500", "Internal Server Error")
};
self.buffer.extend_from_slice(s.as_bytes());
self.buffer.extend_from_slice(b" ");
self.buffer.extend_from_slice(reason.as_bytes());
self.buffer.extend_from_slice(b"\r\n\r\n")
}
}
}
}
#[derive(Debug)]
pub struct ClientRequest<'a> {
ws_key: Vec<u8>,
protocols: Vec<&'a str>,
path: String,
}
impl<'a> ClientRequest<'a> {
pub fn key(&self) -> &[u8] {
&self.ws_key
}
pub fn into_key(self) -> Vec<u8> {
self.ws_key
}
pub fn protocols(&self) -> impl Iterator<Item = &str> {
self.protocols.iter().cloned()
}
pub fn path(&self) -> &str {
&self.path
}
}
#[derive(Debug)]
pub enum Response<'a> {
Accept {
key: &'a [u8],
protocol: Option<&'a str>
},
Reject {
status_code: u16
}
}
const STATUSCODES: &[(u16, &str, &str)] = &[
(100, "100", "Continue"),
(101, "101", "Switching Protocols"),
(102, "102", "Processing"),
(200, "200", "OK"),
(201, "201", "Created"),
(202, "202", "Accepted"),
(203, "203", "Non Authoritative Information"),
(204, "204", "No Content"),
(205, "205", "Reset Content"),
(206, "206", "Partial Content"),
(207, "207", "Multi-Status"),
(208, "208", "Already Reported"),
(226, "226", "IM Used"),
(300, "300", "Multiple Choices"),
(301, "301", "Moved Permanently"),
(302, "302", "Found"),
(303, "303", "See Other"),
(304, "304", "Not Modified"),
(305, "305", "Use Proxy"),
(307, "307", "Temporary Redirect"),
(308, "308", "Permanent Redirect"),
(400, "400", "Bad Request"),
(401, "401", "Unauthorized"),
(402, "402", "Payment Required"),
(403, "403", "Forbidden"),
(404, "404", "Not Found"),
(405, "405", "Method Not Allowed"),
(406, "406", "Not Acceptable"),
(407, "407", "Proxy Authentication Required"),
(408, "408", "Request Timeout"),
(409, "409", "Conflict"),
(410, "410", "Gone"),
(411, "411", "Length Required"),
(412, "412", "Precondition Failed"),
(413, "413", "Payload Too Large"),
(414, "414", "URI Too Long"),
(415, "415", "Unsupported Media Type"),
(416, "416", "Range Not Satisfiable"),
(417, "417", "Expectation Failed"),
(418, "418", "I'm a teapot"),
(421, "421", "Misdirected Request"),
(422, "422", "Unprocessable Entity"),
(423, "423", "Locked"),
(424, "424", "Failed Dependency"),
(426, "426", "Upgrade Required"),
(428, "428", "Precondition Required"),
(429, "429", "Too Many Requests"),
(431, "431", "Request Header Fields Too Large"),
(451, "451", "Unavailable For Legal Reasons"),
(500, "500", "Internal Server Error"),
(501, "501", "Not Implemented"),
(502, "502", "Bad Gateway"),
(503, "503", "Service Unavailable"),
(504, "504", "Gateway Timeout"),
(505, "505", "HTTP Version Not Supported"),
(506, "506", "Variant Also Negotiates"),
(507, "507", "Insufficient Storage"),
(508, "508", "Loop Detected"),
(510, "510", "Not Extended"),
(511, "511", "Network Authentication Required")
];