Skip to main content

tungstenite/handshake/
client.rs

1//! Client handshake machine.
2
3use std::{
4    io::{Read, Write},
5    marker::PhantomData,
6};
7
8use headers::{Header, HeaderMapExt};
9use http::{
10    header::HeaderName, HeaderMap, Request as HttpRequest, Response as HttpResponse, StatusCode,
11};
12use httparse::Status;
13use log::*;
14
15use super::{
16    derive_accept_key,
17    headers::{FromHttparse, MAX_HEADERS},
18    machine::{HandshakeMachine, StageResult, TryParse},
19    HandshakeRole, MidHandshake, ProcessingResult,
20};
21use crate::{
22    error::{Error, ProtocolError, Result, SubProtocolError, UrlError},
23    extensions::{headers::SecWebsocketExtensions, Extensions, ExtensionsConfig},
24    handshake::version_as_str,
25    protocol::{Role, WebSocket, WebSocketConfig},
26};
27
28/// Client request type.
29pub type Request = HttpRequest<()>;
30
31/// Client response type.
32pub type Response = HttpResponse<Option<Vec<u8>>>;
33
34/// Client handshake role.
35#[derive(Debug)]
36pub struct ClientHandshake<S> {
37    verify_data: VerifyData,
38    config: Option<WebSocketConfig>,
39    _marker: PhantomData<S>,
40}
41
42impl<S: Read + Write> ClientHandshake<S> {
43    /// Initiate a client handshake.
44    pub fn start(
45        stream: S,
46        request: Request,
47        config: Option<WebSocketConfig>,
48    ) -> Result<MidHandshake<Self>> {
49        if request.method() != http::Method::GET {
50            return Err(Error::Protocol(ProtocolError::WrongHttpMethod));
51        }
52
53        if request.version() < http::Version::HTTP_11 {
54            return Err(Error::Protocol(ProtocolError::WrongHttpVersion));
55        }
56
57        // Check the URI scheme: only ws or wss are supported
58        let _ = crate::client::uri_mode(request.uri())?;
59
60        let subprotocols = extract_subprotocols_from_request(&request)?;
61
62        // Convert and verify the `http::Request` and turn it into the request as per RFC.
63        // Also extract the key from it (it must be present in a correct request).
64        let (request, key) = generate_request(request, config.as_ref().map(|w| &w.extensions))?;
65
66        let machine = HandshakeMachine::start_write(stream, request);
67
68        let client = {
69            let accept_key = derive_accept_key(key.as_ref());
70            ClientHandshake {
71                verify_data: VerifyData { accept_key, subprotocols },
72                config,
73                _marker: PhantomData,
74            }
75        };
76
77        trace!("Client handshake initiated.");
78        Ok(MidHandshake { role: client, machine })
79    }
80}
81
82impl<S: Read + Write> HandshakeRole for ClientHandshake<S> {
83    type IncomingData = Response;
84    type InternalStream = S;
85    type FinalResult = (WebSocket<S>, Response);
86    fn stage_finished(
87        &mut self,
88        finish: StageResult<Self::IncomingData, Self::InternalStream>,
89    ) -> Result<ProcessingResult<Self::InternalStream, Self::FinalResult>> {
90        Ok(match finish {
91            StageResult::DoneWriting(stream) => {
92                ProcessingResult::Continue(HandshakeMachine::start_read(stream))
93            }
94            StageResult::DoneReading { stream, result, tail } => {
95                let (result, extensions) = match self
96                    .verify_data
97                    .verify_response(result, self.config.as_ref().map(|c| &c.extensions))
98                {
99                    Ok(r) => r,
100                    Err(Error::Http(mut e)) => {
101                        *e.body_mut() = Some(tail);
102                        return Err(Error::Http(e));
103                    }
104                    Err(e) => return Err(e),
105                };
106
107                debug!("Client handshake done.");
108                let websocket = WebSocket::from_partially_read_with_extensions(
109                    stream,
110                    tail,
111                    Role::Client,
112                    self.config,
113                    extensions,
114                );
115                ProcessingResult::Done((websocket, result))
116            }
117        })
118    }
119}
120
121/// Verifies and generates a client WebSocket request from the original request and extracts a WebSocket key from it.
122pub fn generate_request(
123    mut request: Request,
124    extensions: Option<&ExtensionsConfig>,
125) -> Result<(Vec<u8>, String)> {
126    let mut req = Vec::new();
127    write!(
128        req,
129        "GET {path} {version}\r\n",
130        path = request.uri().path_and_query().ok_or(Error::Url(UrlError::NoPathOrQuery))?.as_str(),
131        version = version_as_str(request.version())?,
132    )
133    .unwrap();
134
135    // Headers that must be present in a correct request.
136    const KEY_HEADERNAME: &str = "Sec-WebSocket-Key";
137    const WEBSOCKET_HEADERS: [&str; 5] =
138        ["Host", "Connection", "Upgrade", "Sec-WebSocket-Version", KEY_HEADERNAME];
139
140    // We must extract a WebSocket key from a properly formed request or fail if it's not present.
141    let key = request
142        .headers()
143        .get(KEY_HEADERNAME)
144        .ok_or_else(|| {
145            Error::Protocol(ProtocolError::InvalidHeader(
146                HeaderName::from_bytes(KEY_HEADERNAME.as_bytes()).unwrap().into(),
147            ))
148        })?
149        .to_str()?
150        .to_owned();
151
152    // We must check that all necessary headers for a valid request are present. Note that we have to
153    // deal with the fact that some apps seem to have a case-sensitive check for headers which is not
154    // correct and should not considered the correct behavior, but it seems like some apps ignore it.
155    // `http` by default writes all headers in lower-case which is fine (and does not violate the RFC)
156    // but some servers seem to be poorely written and ignore RFC.
157    //
158    // See similar problem in `hyper`: https://github.com/hyperium/hyper/issues/1492
159    let headers = request.headers_mut();
160    for &header in &WEBSOCKET_HEADERS {
161        let value = headers.remove(header).ok_or_else(|| {
162            Error::Protocol(ProtocolError::InvalidHeader(
163                HeaderName::from_bytes(header.as_bytes()).unwrap().into(),
164            ))
165        })?;
166        write!(
167            req,
168            "{header}: {value}\r\n",
169            header = header,
170            value = value.to_str().map_err(|err| {
171                Error::Utf8(format!("{err} for header name '{header}' with value: {value:?}"))
172            })?
173        )
174        .unwrap();
175    }
176
177    if let Some(header) = extensions
178        .map(ExtensionsConfig::generate_offers)
179        .map(SecWebsocketExtensions::new)
180        .filter(|header| header.len() != 0)
181    {
182        headers.append(SecWebsocketExtensions::name(), header.header_value());
183    }
184
185    // Now we must ensure that the headers that we've written once are not anymore present in the map.
186    // If they do, then the request is invalid (some headers are duplicated there for some reason).
187    let websocket_headers_contains =
188        |name| WEBSOCKET_HEADERS.iter().any(|h| h.eq_ignore_ascii_case(name));
189
190    for (k, v) in headers {
191        let mut name = k.as_str();
192
193        // We have already written the necessary headers once (above) and removed them from the map.
194        // If we encounter them again, then the request is considered invalid and error is returned.
195        if websocket_headers_contains(name) {
196            return Err(Error::Protocol(ProtocolError::InvalidHeader(k.clone().into())));
197        }
198
199        // Relates to the issue of some servers treating headers in a case-sensitive way, please see:
200        // https://github.com/snapview/tungstenite-rs/pull/119 (original fix of the problem)
201        if name == "sec-websocket-protocol" {
202            name = "Sec-WebSocket-Protocol";
203        }
204
205        if name == "origin" {
206            name = "Origin";
207        }
208
209        writeln!(
210            req,
211            "{}: {}\r",
212            name,
213            v.to_str().map_err(|err| {
214                Error::Utf8(format!("{err} for header name '{name}' with value: {v:?}"))
215            })?
216        )
217        .unwrap();
218    }
219
220    writeln!(req, "\r").unwrap();
221    trace!("Request: {:?}", String::from_utf8_lossy(&req));
222    Ok((req, key))
223}
224
225fn extract_subprotocols_from_request(request: &Request) -> Result<Option<Vec<String>>> {
226    if let Some(subprotocols) = request.headers().get("Sec-WebSocket-Protocol") {
227        Ok(Some(subprotocols.to_str()?.split(',').map(|s| s.trim().to_string()).collect()))
228    } else {
229        Ok(None)
230    }
231}
232
233/// Information for handshake verification.
234#[derive(Debug)]
235struct VerifyData {
236    /// Accepted server key.
237    accept_key: String,
238
239    /// Accepted subprotocols
240    subprotocols: Option<Vec<String>>,
241}
242
243impl VerifyData {
244    pub fn verify_response(
245        &self,
246        response: Response,
247        extensions: Option<&ExtensionsConfig>,
248    ) -> Result<(Response, Extensions)> {
249        // 1. If the status code received from the server is not 101, the
250        // client handles the response per HTTP [RFC2616] procedures. (RFC 6455)
251        if response.status() != StatusCode::SWITCHING_PROTOCOLS {
252            return Err(Error::Http(response.into()));
253        }
254
255        let headers = response.headers();
256
257        // 2. If the response lacks an |Upgrade| header field or the |Upgrade|
258        // header field contains a value that is not an ASCII case-
259        // insensitive match for the value "websocket", the client MUST
260        // _Fail the WebSocket Connection_. (RFC 6455)
261        if !headers
262            .get("Upgrade")
263            .and_then(|h| h.to_str().ok())
264            .map(|h| h.eq_ignore_ascii_case("websocket"))
265            .unwrap_or(false)
266        {
267            return Err(Error::Protocol(ProtocolError::MissingUpgradeWebSocketHeader));
268        }
269        // 3.  If the response lacks a |Connection| header field or the
270        // |Connection| header field doesn't contain a token that is an
271        // ASCII case-insensitive match for the value "Upgrade", the client
272        // MUST _Fail the WebSocket Connection_. (RFC 6455)
273        if !headers
274            .get("Connection")
275            .and_then(|h| h.to_str().ok())
276            .map(|h| h.eq_ignore_ascii_case("Upgrade"))
277            .unwrap_or(false)
278        {
279            return Err(Error::Protocol(ProtocolError::MissingConnectionUpgradeHeader));
280        }
281        // 4.  If the response lacks a |Sec-WebSocket-Accept| header field or
282        // the |Sec-WebSocket-Accept| contains a value other than the
283        // base64-encoded SHA-1 of ... the client MUST _Fail the WebSocket
284        // Connection_. (RFC 6455)
285        if !headers.get("Sec-WebSocket-Accept").map(|h| h == &self.accept_key).unwrap_or(false) {
286            return Err(Error::Protocol(ProtocolError::SecWebSocketAcceptKeyMismatch));
287        }
288        // 5.  If the response includes a |Sec-WebSocket-Extensions| header
289        // field and this header field indicates the use of an extension
290        // that was not present in the client's handshake (the server has
291        // indicated an extension not requested by the client), the client
292        // MUST _Fail the WebSocket Connection_. (RFC 6455)
293        let extensions_header =
294            headers.typed_try_get::<SecWebsocketExtensions>().map_err(|_| {
295                ProtocolError::InvalidHeader(SecWebsocketExtensions::name().clone().into())
296            })?;
297
298        let extensions = match extensions_header {
299            None => Extensions::default(),
300            Some(agreed) => extensions
301                .ok_or(ProtocolError::InvalidHeader(SecWebsocketExtensions::name().clone().into()))?
302                .verify_agreed_on(agreed)
303                .map_err(ProtocolError::from)?,
304        };
305
306        // 6.  If the response includes a |Sec-WebSocket-Protocol| header field
307        // and this header field indicates the use of a subprotocol that was
308        // not present in the client's handshake (the server has indicated a
309        // subprotocol not requested by the client), the client MUST _Fail
310        // the WebSocket Connection_. (RFC 6455)
311        if headers.get("Sec-WebSocket-Protocol").is_none() && self.subprotocols.is_some() {
312            return Err(Error::Protocol(ProtocolError::SecWebSocketSubProtocolError(
313                SubProtocolError::NoSubProtocol,
314            )));
315        }
316
317        if headers.get("Sec-WebSocket-Protocol").is_some() && self.subprotocols.is_none() {
318            return Err(Error::Protocol(ProtocolError::SecWebSocketSubProtocolError(
319                SubProtocolError::ServerSentSubProtocolNoneRequested,
320            )));
321        }
322
323        if let Some(returned_subprotocol) = headers.get("Sec-WebSocket-Protocol") {
324            if let Some(accepted_subprotocols) = &self.subprotocols {
325                if !accepted_subprotocols.contains(&returned_subprotocol.to_str()?.to_string()) {
326                    return Err(Error::Protocol(ProtocolError::SecWebSocketSubProtocolError(
327                        SubProtocolError::InvalidSubProtocol,
328                    )));
329                }
330            }
331        }
332
333        Ok((response, extensions))
334    }
335}
336
337impl TryParse for Response {
338    fn try_parse(buf: &[u8]) -> Result<Option<(usize, Self)>> {
339        let mut hbuffer = [httparse::EMPTY_HEADER; MAX_HEADERS];
340        let mut req = httparse::Response::new(&mut hbuffer);
341        Ok(match req.parse(buf)? {
342            Status::Partial => None,
343            Status::Complete(size) => Some((size, Response::from_httparse(req)?)),
344        })
345    }
346}
347
348impl<'h, 'b: 'h> FromHttparse<httparse::Response<'h, 'b>> for Response {
349    fn from_httparse(raw: httparse::Response<'h, 'b>) -> Result<Self> {
350        if raw.version.expect("Bug: no HTTP version") < /*1.*/1 {
351            return Err(Error::Protocol(ProtocolError::WrongHttpVersion));
352        }
353
354        let headers = HeaderMap::from_httparse(raw.headers)?;
355
356        let mut response = Response::new(None);
357        *response.status_mut() = StatusCode::from_u16(raw.code.expect("Bug: no HTTP status code"))?;
358        *response.headers_mut() = headers;
359        // TODO: httparse only supports HTTP 0.9/1.0/1.1 but not HTTP 2.0
360        // so the only valid value we could get in the response would be 1.1.
361        *response.version_mut() = http::Version::HTTP_11;
362
363        Ok(response)
364    }
365}
366
367/// Generate a random key for the `Sec-WebSocket-Key` header.
368pub fn generate_key() -> String {
369    // a base64-encoded (see Section 4 of [RFC4648]) value that,
370    // when decoded, is 16 bytes in length (RFC 6455)
371    let r: [u8; 16] = rand::random();
372    data_encoding::BASE64.encode(&r)
373}
374
375#[cfg(test)]
376mod tests {
377    use super::{super::machine::TryParse, generate_key, generate_request, Response};
378    use crate::client::IntoClientRequest;
379
380    #[test]
381    fn random_keys() {
382        let k1 = generate_key();
383        println!("Generated random key 1: {k1}");
384        let k2 = generate_key();
385        println!("Generated random key 2: {k2}");
386        assert_ne!(k1, k2);
387        assert_eq!(k1.len(), k2.len());
388        assert_eq!(k1.len(), 24);
389        assert_eq!(k2.len(), 24);
390        assert!(k1.ends_with("=="));
391        assert!(k2.ends_with("=="));
392        assert!(k1[..22].find('=').is_none());
393        assert!(k2[..22].find('=').is_none());
394    }
395
396    fn construct_expected(host: &str, key: &str) -> Vec<u8> {
397        format!(
398            "\
399            GET /getCaseCount HTTP/1.1\r\n\
400            Host: {host}\r\n\
401            Connection: Upgrade\r\n\
402            Upgrade: websocket\r\n\
403            Sec-WebSocket-Version: 13\r\n\
404            Sec-WebSocket-Key: {key}\r\n\
405            \r\n"
406        )
407        .into_bytes()
408    }
409
410    #[test]
411    fn request_formatting() {
412        let request = "ws://localhost/getCaseCount".into_client_request().unwrap();
413        let (request, key) = generate_request(request, None).unwrap();
414        let correct = construct_expected("localhost", &key);
415        assert_eq!(&request[..], &correct[..]);
416    }
417
418    #[test]
419    fn request_formatting_with_host() {
420        let request = "wss://localhost:9001/getCaseCount".into_client_request().unwrap();
421        let (request, key) = generate_request(request, None).unwrap();
422        let correct = construct_expected("localhost:9001", &key);
423        assert_eq!(&request[..], &correct[..]);
424    }
425
426    #[test]
427    fn request_formatting_with_at() {
428        let request = "wss://user:pass@localhost:9001/getCaseCount".into_client_request().unwrap();
429        let (request, key) = generate_request(request, None).unwrap();
430        let correct = construct_expected("localhost:9001", &key);
431        assert_eq!(&request[..], &correct[..]);
432    }
433
434    #[cfg(feature = "deflate")]
435    #[test]
436    fn request_with_compression() {
437        use crate::extensions::{compression::deflate::DeflateConfig, ExtensionsConfig};
438
439        let request = "ws://localhost/getCaseCount".into_client_request().unwrap();
440        let (request, key) = generate_request(
441            request,
442            Some(&ExtensionsConfig {
443                permessage_deflate: Some(DeflateConfig::default()),
444                ..ExtensionsConfig::default()
445            }),
446        )
447        .unwrap();
448        let correct = format!(
449            "\
450            GET /getCaseCount HTTP/1.1\r\n\
451            Host: {host}\r\n\
452            Connection: Upgrade\r\n\
453            Upgrade: websocket\r\n\
454            Sec-WebSocket-Version: 13\r\n\
455            Sec-WebSocket-Key: {key}\r\n\
456            sec-websocket-extensions: permessage-deflate; client_max_window_bits\r\n\
457            \r\n",
458            host = "localhost",
459            key = key
460        );
461        assert_eq!(String::try_from(request).unwrap(), &correct[..]);
462    }
463
464    #[test]
465    fn response_parsing() {
466        const DATA: &[u8] = b"HTTP/1.1 200 OK\r\nContent-Type: text/html\r\n\r\n";
467        let (_, resp) = Response::try_parse(DATA).unwrap().unwrap();
468        assert_eq!(resp.status(), http::StatusCode::OK);
469        assert_eq!(resp.headers().get("Content-Type").unwrap(), &b"text/html"[..],);
470    }
471
472    #[test]
473    fn invalid_custom_request() {
474        let request = http::Request::builder().method("GET").body(()).unwrap();
475        assert!(generate_request(request, None).is_err());
476    }
477}