tungstenite/handshake/
client.rs

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