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
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;
#[derive(Debug)]
pub struct Client<'a, T> {
socket: T,
host: &'a str,
resource: &'a str,
origin: Option<&'a str>,
nonce: [u8; 32],
nonce_offset: usize,
protocols: Vec<&'a str>,
extensions: Vec<Box<dyn Extension + Send>>,
buffer: BytesMut
}
impl<'a, T: AsyncRead + AsyncWrite + Unpin> Client<'a, T> {
pub fn new(socket: T, host: &'a str, resource: &'a str) -> Self {
Client {
socket,
host,
resource,
origin: None,
nonce: [0; 32],
nonce_offset: 0,
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 set_origin(&mut self, o: &'a str) -> &mut Self {
self.origin = Some(o);
self
}
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 handshake(&mut self) -> Result<ServerResponse, Error> {
self.buffer.clear();
self.encode_request();
self.socket.write_all(&self.buffer).await?;
self.socket.flush().await?;
self.buffer.clear();
loop {
crate::read(&mut self.socket, &mut self.buffer, BLOCK_SIZE).await?;
if let Parsing::Done { value, offset } = self.decode_response()? {
self.buffer.advance(offset);
return Ok(value)
}
}
}
pub fn into_builder(mut self) -> connection::Builder<T> {
let mut builder = connection::Builder::new(self.socket, Mode::Client);
builder.set_buffer(self.buffer);
builder.add_extensions(self.extensions.drain(..));
builder
}
pub fn into_inner(self) -> T {
self.socket
}
fn encode_request(&mut self) {
let nonce: [u8; 16] = rand::random();
self.nonce_offset = base64::encode_config_slice(&nonce, base64::STANDARD, &mut self.nonce);
self.buffer.extend_from_slice(b"GET ");
self.buffer.extend_from_slice(self.resource.as_bytes());
self.buffer.extend_from_slice(b" HTTP/1.1");
self.buffer.extend_from_slice(b"\r\nHost: ");
self.buffer.extend_from_slice(self.host.as_bytes());
self.buffer.extend_from_slice(b"\r\nUpgrade: websocket\r\nConnection: upgrade");
self.buffer.extend_from_slice(b"\r\nSec-WebSocket-Key: ");
self.buffer.extend_from_slice(&self.nonce[.. self.nonce_offset]);
if let Some(o) = &self.origin {
self.buffer.extend_from_slice(b"\r\nOrigin: ");
self.buffer.extend_from_slice(o.as_bytes())
}
if let Some((last, prefix)) = self.protocols.split_last() {
self.buffer.extend_from_slice(b"\r\nSec-WebSocket-Protocol: ");
for p in prefix {
self.buffer.extend_from_slice(p.as_bytes());
self.buffer.extend_from_slice(b",")
}
self.buffer.extend_from_slice(last.as_bytes())
}
append_extensions(&self.extensions, &mut self.buffer);
self.buffer.extend_from_slice(b"\r\nSec-WebSocket-Version: 13\r\n\r\n")
}
fn decode_response(&mut self) -> Result<Parsing<ServerResponse>, Error> {
let mut header_buf = [httparse::EMPTY_HEADER; MAX_NUM_HEADERS];
let mut response = httparse::Response::new(&mut header_buf);
let offset = match response.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 response.version != Some(1) {
return Err(Error::UnsupportedHttpVersion)
}
match response.code {
Some(101) => (),
Some(code@(301 ..= 303)) | Some(code@307) | Some(code@308) => {
let location = with_first_header(response.headers, "Location", |loc| {
Ok(String::from(std::str::from_utf8(loc)?))
})?;
let response = ServerResponse::Redirect { status_code: code, location };
return Ok(Parsing::Done { value: response, offset })
}
other => {
let response = ServerResponse::Rejected { status_code: other.unwrap_or(0) };
return Ok(Parsing::Done { value: response, offset })
}
}
expect_ascii_header(response.headers, "Upgrade", "websocket")?;
expect_ascii_header(response.headers, "Connection", "upgrade")?;
let nonce = &self.nonce[.. self.nonce_offset];
with_first_header(&response.headers, "Sec-WebSocket-Accept", |theirs| {
let mut digest = Sha1::new();
digest.update(nonce);
digest.update(KEY);
let ours = base64::encode(&digest.finalize());
if ours.as_bytes() != theirs {
return Err(Error::InvalidSecWebSocketAccept)
}
Ok(())
})?;
for h in response.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 selected_proto = None;
if let Some(tp) = response.headers.iter()
.find(|h| h.name.eq_ignore_ascii_case(SEC_WEBSOCKET_PROTOCOL))
{
if let Some(&p) = self.protocols.iter().find(|x| x.as_bytes() == tp.value) {
selected_proto = Some(String::from(p))
} else {
return Err(Error::UnsolicitedProtocol)
}
}
let response = ServerResponse::Accepted { protocol: selected_proto };
Ok(Parsing::Done { value: response, offset })
}
}
#[derive(Debug)]
pub enum ServerResponse {
Accepted {
protocol: Option<String>
},
Redirect {
status_code: u16,
location: String
},
Rejected {
status_code: u16
}
}