1
0
mirror of https://github.com/fafhrd91/actix-web synced 2025-03-03 15:37:34 +01:00

353 lines
11 KiB
Rust
Raw Normal View History

2021-02-28 19:55:34 +00:00
//! WebSocket protocol implementation.
2017-10-07 22:41:02 -07:00
//!
2021-02-12 00:27:20 +00:00
//! To setup a WebSocket, first perform the WebSocket handshake then on success convert `Payload` into a
//! `WsStream` stream and then use `WsWriter` to communicate with the peer.
2018-10-05 12:47:22 -07:00
use std::io;
2017-10-07 21:48:00 -07:00
use derive_more::{Display, Error, From};
2018-10-05 12:47:22 -07:00
use http::{header, Method, StatusCode};
2018-12-06 14:32:52 -08:00
2021-02-28 19:55:34 +00:00
use crate::{
2021-06-17 17:57:58 +01:00
body::AnyBody, header::HeaderValue, message::RequestHead, response::Response,
ResponseBuilder,
2021-02-28 19:55:34 +00:00
};
2017-10-07 21:48:00 -07:00
2018-10-05 12:47:22 -07:00
mod codec;
2019-12-11 19:20:20 +06:00
mod dispatcher;
2018-04-13 16:02:01 -07:00
mod frame;
mod mask;
2018-04-13 16:02:01 -07:00
mod proto;
2018-01-10 11:13:29 -08:00
pub use self::codec::{Codec, Frame, Item, Message};
2019-12-11 19:20:20 +06:00
pub use self::dispatcher::Dispatcher;
2018-10-10 13:20:00 -07:00
pub use self::frame::Parser;
2019-03-17 21:09:50 -07:00
pub use self::proto::{hash_key, CloseCode, CloseReason, OpCode};
/// WebSocket protocol errors.
2021-06-17 17:57:58 +01:00
#[derive(Debug, Display, Error, From)]
pub enum ProtocolError {
/// Received an unmasked frame from client.
#[display(fmt = "Received an unmasked frame from client.")]
2018-02-27 10:09:24 -08:00
UnmaskedFrame,
/// Received a masked frame from server.
#[display(fmt = "Received a masked frame from server.")]
2018-02-27 10:09:24 -08:00
MaskedFrame,
/// Encountered invalid opcode.
#[display(fmt = "Invalid opcode: {}.", _0)]
InvalidOpcode(#[error(not(source))] u8),
2018-02-27 10:09:24 -08:00
/// Invalid control frame length
#[display(fmt = "Invalid control frame length: {}.", _0)]
InvalidLength(#[error(not(source))] usize),
/// Bad opcode.
#[display(fmt = "Bad opcode.")]
2018-02-27 10:09:24 -08:00
BadOpCode,
2018-02-27 10:09:24 -08:00
/// A payload reached size limit.
2018-12-19 18:34:56 -08:00
#[display(fmt = "A payload reached size limit.")]
2018-02-27 10:09:24 -08:00
Overflow,
/// Continuation is not started.
#[display(fmt = "Continuation is not started.")]
ContinuationNotStarted,
/// Received new continuation but it is already started.
#[display(fmt = "Received new continuation but it is already started.")]
ContinuationStarted,
/// Unknown continuation fragment.
#[display(fmt = "Unknown continuation fragment: {}.", _0)]
ContinuationFragment(#[error(not(source))] OpCode),
/// I/O error.
#[display(fmt = "I/O error: {}", _0)]
2018-12-19 18:34:56 -08:00
Io(io::Error),
2018-02-27 10:09:24 -08:00
}
/// WebSocket handshake errors
2021-06-17 17:57:58 +01:00
#[derive(Debug, PartialEq, Display, Error)]
pub enum HandshakeError {
/// Only get method is allowed.
#[display(fmt = "Method not allowed.")]
2018-02-27 10:09:24 -08:00
GetMethodRequired,
2021-02-12 00:27:20 +00:00
/// Upgrade header if not set to WebSocket.
#[display(fmt = "WebSocket upgrade is expected.")]
2018-02-27 10:09:24 -08:00
NoWebsocketUpgrade,
/// Connection header is not set to upgrade.
#[display(fmt = "Connection upgrade is expected.")]
2018-02-27 10:09:24 -08:00
NoConnectionUpgrade,
/// WebSocket version header is not set.
#[display(fmt = "WebSocket version header is required.")]
2018-02-27 10:09:24 -08:00
NoVersionHeader,
2021-02-12 00:27:20 +00:00
/// Unsupported WebSocket version.
2021-02-28 19:55:34 +00:00
#[display(fmt = "Unsupported WebSocket version.")]
2018-02-27 10:09:24 -08:00
UnsupportedVersion,
/// WebSocket key is not set or wrong.
#[display(fmt = "Unknown websocket key.")]
2018-02-27 10:09:24 -08:00
BadWebsocketKey,
}
2021-06-17 17:57:58 +01:00
impl From<&HandshakeError> for Response<AnyBody> {
fn from(err: &HandshakeError) -> Self {
match err {
HandshakeError::GetMethodRequired => {
2021-06-17 17:57:58 +01:00
let mut res = Response::new(StatusCode::METHOD_NOT_ALLOWED);
res.headers_mut()
.insert(header::ALLOW, HeaderValue::from_static("GET"));
res
}
HandshakeError::NoWebsocketUpgrade => {
2021-06-17 17:57:58 +01:00
let mut res = Response::bad_request();
res.head_mut().reason = Some("No WebSocket Upgrade header found");
res
}
HandshakeError::NoConnectionUpgrade => {
2021-06-17 17:57:58 +01:00
let mut res = Response::bad_request();
res.head_mut().reason = Some("No Connection upgrade");
res
}
2021-06-17 17:57:58 +01:00
HandshakeError::NoVersionHeader => {
let mut res = Response::bad_request();
res.head_mut().reason = Some("WebSocket version header is required");
res
}
HandshakeError::UnsupportedVersion => {
2021-06-17 17:57:58 +01:00
let mut res = Response::bad_request();
res.head_mut().reason = Some("Unsupported WebSocket version");
res
2018-10-05 11:04:59 -07:00
}
2021-06-17 17:57:58 +01:00
HandshakeError::BadWebsocketKey => {
let mut res = Response::bad_request();
res.head_mut().reason = Some("Handshake error");
res
}
2018-02-27 10:09:24 -08:00
}
}
}
2021-06-17 17:57:58 +01:00
impl From<HandshakeError> for Response<AnyBody> {
fn from(err: HandshakeError) -> Self {
(&err).into()
}
}
2021-02-12 00:27:20 +00:00
/// Verify WebSocket handshake request and create handshake response.
pub fn handshake(req: &RequestHead) -> Result<ResponseBuilder, HandshakeError> {
2018-10-22 09:59:20 -07:00
verify_handshake(req)?;
Ok(handshake_response(req))
}
2021-02-12 00:27:20 +00:00
/// Verify WebSocket handshake request.
pub fn verify_handshake(req: &RequestHead) -> Result<(), HandshakeError> {
2017-10-07 21:48:00 -07:00
// WebSocket accepts only GET
if req.method != Method::GET {
2018-04-13 16:02:01 -07:00
return Err(HandshakeError::GetMethodRequired);
2017-10-07 21:48:00 -07:00
}
2021-02-12 00:27:20 +00:00
// Check for "UPGRADE" to WebSocket header
2017-10-09 23:07:32 -07:00
let has_hdr = if let Some(hdr) = req.headers().get(header::UPGRADE) {
if let Ok(s) = hdr.to_str() {
2019-03-17 22:56:13 -07:00
s.to_ascii_lowercase().contains("websocket")
2017-10-09 23:07:32 -07:00
} else {
false
}
2017-10-07 21:48:00 -07:00
} else {
false
};
if !has_hdr {
2018-04-13 16:02:01 -07:00
return Err(HandshakeError::NoWebsocketUpgrade);
2017-10-07 21:48:00 -07:00
}
// Upgrade connection
2017-10-14 00:11:12 -07:00
if !req.upgrade() {
2018-04-13 16:02:01 -07:00
return Err(HandshakeError::NoConnectionUpgrade);
2017-10-07 21:48:00 -07:00
}
// check supported version
2018-05-17 12:20:20 -07:00
if !req.headers().contains_key(header::SEC_WEBSOCKET_VERSION) {
2018-04-13 16:02:01 -07:00
return Err(HandshakeError::NoVersionHeader);
2017-10-07 21:48:00 -07:00
}
let supported_ver = {
2018-02-28 14:16:55 -08:00
if let Some(hdr) = req.headers().get(header::SEC_WEBSOCKET_VERSION) {
2017-10-09 23:07:32 -07:00
hdr == "13" || hdr == "8" || hdr == "7"
} else {
false
2017-10-07 21:48:00 -07:00
}
};
if !supported_ver {
2018-04-13 16:02:01 -07:00
return Err(HandshakeError::UnsupportedVersion);
2017-10-07 21:48:00 -07:00
}
// check client handshake for validity
2018-02-28 14:16:55 -08:00
if !req.headers().contains_key(header::SEC_WEBSOCKET_KEY) {
2018-04-13 16:02:01 -07:00
return Err(HandshakeError::BadWebsocketKey);
2017-10-09 23:07:32 -07:00
}
2018-10-22 09:59:20 -07:00
Ok(())
}
2021-02-12 00:27:20 +00:00
/// Create WebSocket handshake response.
2018-10-22 09:59:20 -07:00
///
/// This function returns handshake `Response`, ready to send to peer.
pub fn handshake_response(req: &RequestHead) -> ResponseBuilder {
2017-10-09 23:07:32 -07:00
let key = {
2018-02-28 14:16:55 -08:00
let key = req.headers().get(header::SEC_WEBSOCKET_KEY).unwrap();
2018-03-09 13:03:15 -08:00
proto::hash_key(key.as_ref())
2017-10-07 21:48:00 -07:00
};
2018-10-22 09:59:20 -07:00
Response::build(StatusCode::SWITCHING_PROTOCOLS)
2018-11-19 14:57:12 -08:00
.upgrade("websocket")
2021-02-28 19:55:34 +00:00
.insert_header((
header::SEC_WEBSOCKET_ACCEPT,
// key is known to be header value safe ascii
HeaderValue::from_bytes(&key).unwrap(),
))
2018-10-22 09:59:20 -07:00
.take()
2017-10-07 21:48:00 -07:00
}
2017-10-22 17:33:24 -07:00
#[cfg(test)]
mod tests {
2017-11-15 20:06:28 -10:00
use super::*;
2021-06-17 17:57:58 +01:00
use crate::{body::AnyBody, test::TestRequest};
2018-07-04 21:01:27 +06:00
use http::{header, Method};
2017-10-22 17:33:24 -07:00
#[test]
fn test_handshake() {
2018-06-25 10:58:04 +06:00
let req = TestRequest::default().method(Method::POST).finish();
2018-04-29 09:09:08 -07:00
assert_eq!(
HandshakeError::GetMethodRequired,
2020-12-23 01:28:17 +00:00
verify_handshake(req.head()).unwrap_err(),
2018-04-29 09:09:08 -07:00
);
2018-04-13 16:02:01 -07:00
2018-06-25 10:58:04 +06:00
let req = TestRequest::default().finish();
2018-04-29 09:09:08 -07:00
assert_eq!(
HandshakeError::NoWebsocketUpgrade,
2020-12-23 01:28:17 +00:00
verify_handshake(req.head()).unwrap_err(),
2018-04-29 09:09:08 -07:00
);
2017-10-22 17:33:24 -07:00
2018-06-25 10:58:04 +06:00
let req = TestRequest::default()
2021-01-15 02:11:10 +00:00
.insert_header((header::UPGRADE, header::HeaderValue::from_static("test")))
2018-06-25 10:58:04 +06:00
.finish();
2018-04-29 09:09:08 -07:00
assert_eq!(
HandshakeError::NoWebsocketUpgrade,
2020-12-23 01:28:17 +00:00
verify_handshake(req.head()).unwrap_err(),
2018-04-29 09:09:08 -07:00
);
2017-10-22 17:33:24 -07:00
2018-06-25 10:58:04 +06:00
let req = TestRequest::default()
2021-01-15 02:11:10 +00:00
.insert_header((
2018-06-25 10:58:04 +06:00
header::UPGRADE,
header::HeaderValue::from_static("websocket"),
2021-01-15 02:11:10 +00:00
))
2018-12-06 14:32:52 -08:00
.finish();
2018-04-29 09:09:08 -07:00
assert_eq!(
HandshakeError::NoConnectionUpgrade,
2020-12-23 01:28:17 +00:00
verify_handshake(req.head()).unwrap_err(),
2018-04-29 09:09:08 -07:00
);
2017-10-22 17:33:24 -07:00
2018-06-25 10:58:04 +06:00
let req = TestRequest::default()
2021-01-15 02:11:10 +00:00
.insert_header((
2018-06-25 10:58:04 +06:00
header::UPGRADE,
header::HeaderValue::from_static("websocket"),
2021-01-15 02:11:10 +00:00
))
.insert_header((
2018-06-25 10:58:04 +06:00
header::CONNECTION,
header::HeaderValue::from_static("upgrade"),
2021-01-15 02:11:10 +00:00
))
2018-12-06 14:32:52 -08:00
.finish();
2018-04-29 09:09:08 -07:00
assert_eq!(
HandshakeError::NoVersionHeader,
2020-12-23 01:28:17 +00:00
verify_handshake(req.head()).unwrap_err(),
2018-04-29 09:09:08 -07:00
);
2017-10-22 17:33:24 -07:00
2018-06-25 10:58:04 +06:00
let req = TestRequest::default()
2021-01-15 02:11:10 +00:00
.insert_header((
2018-06-25 10:58:04 +06:00
header::UPGRADE,
header::HeaderValue::from_static("websocket"),
2021-01-15 02:11:10 +00:00
))
.insert_header((
2018-06-25 10:58:04 +06:00
header::CONNECTION,
header::HeaderValue::from_static("upgrade"),
2021-01-15 02:11:10 +00:00
))
.insert_header((
2018-06-25 10:58:04 +06:00
header::SEC_WEBSOCKET_VERSION,
header::HeaderValue::from_static("5"),
2021-01-15 02:11:10 +00:00
))
2018-12-06 14:32:52 -08:00
.finish();
2018-04-29 09:09:08 -07:00
assert_eq!(
HandshakeError::UnsupportedVersion,
2020-12-23 01:28:17 +00:00
verify_handshake(req.head()).unwrap_err(),
2018-04-29 09:09:08 -07:00
);
2017-10-22 17:33:24 -07:00
2018-06-25 10:58:04 +06:00
let req = TestRequest::default()
2021-01-15 02:11:10 +00:00
.insert_header((
2018-06-25 10:58:04 +06:00
header::UPGRADE,
header::HeaderValue::from_static("websocket"),
2021-01-15 02:11:10 +00:00
))
.insert_header((
2018-06-25 10:58:04 +06:00
header::CONNECTION,
header::HeaderValue::from_static("upgrade"),
2021-01-15 02:11:10 +00:00
))
.insert_header((
2018-06-25 10:58:04 +06:00
header::SEC_WEBSOCKET_VERSION,
header::HeaderValue::from_static("13"),
2021-01-15 02:11:10 +00:00
))
2018-12-06 14:32:52 -08:00
.finish();
2018-04-29 09:09:08 -07:00
assert_eq!(
HandshakeError::BadWebsocketKey,
2020-12-23 01:28:17 +00:00
verify_handshake(req.head()).unwrap_err(),
2018-04-29 09:09:08 -07:00
);
2017-10-22 17:33:24 -07:00
2018-06-25 10:58:04 +06:00
let req = TestRequest::default()
2021-01-15 02:11:10 +00:00
.insert_header((
2018-06-25 10:58:04 +06:00
header::UPGRADE,
header::HeaderValue::from_static("websocket"),
2021-01-15 02:11:10 +00:00
))
.insert_header((
2018-06-25 10:58:04 +06:00
header::CONNECTION,
header::HeaderValue::from_static("upgrade"),
2021-01-15 02:11:10 +00:00
))
.insert_header((
2018-06-25 10:58:04 +06:00
header::SEC_WEBSOCKET_VERSION,
header::HeaderValue::from_static("13"),
2021-01-15 02:11:10 +00:00
))
.insert_header((
2018-06-25 10:58:04 +06:00
header::SEC_WEBSOCKET_KEY,
header::HeaderValue::from_static("13"),
2021-01-15 02:11:10 +00:00
))
2018-12-06 14:32:52 -08:00
.finish();
2018-04-13 16:02:01 -07:00
assert_eq!(
StatusCode::SWITCHING_PROTOCOLS,
handshake_response(req.head()).finish().status()
2018-04-13 16:02:01 -07:00
);
2017-10-22 17:33:24 -07:00
}
2018-02-27 10:09:24 -08:00
#[test]
2021-06-17 17:57:58 +01:00
fn test_ws_error_http_response() {
let resp: Response<AnyBody> = HandshakeError::GetMethodRequired.into();
2018-02-27 10:09:24 -08:00
assert_eq!(resp.status(), StatusCode::METHOD_NOT_ALLOWED);
2021-06-17 17:57:58 +01:00
let resp: Response<AnyBody> = HandshakeError::NoWebsocketUpgrade.into();
2018-02-27 10:09:24 -08:00
assert_eq!(resp.status(), StatusCode::BAD_REQUEST);
2021-06-17 17:57:58 +01:00
let resp: Response<AnyBody> = HandshakeError::NoConnectionUpgrade.into();
2018-02-27 10:09:24 -08:00
assert_eq!(resp.status(), StatusCode::BAD_REQUEST);
2021-06-17 17:57:58 +01:00
let resp: Response<AnyBody> = HandshakeError::NoVersionHeader.into();
2018-02-27 10:09:24 -08:00
assert_eq!(resp.status(), StatusCode::BAD_REQUEST);
2021-06-17 17:57:58 +01:00
let resp: Response<AnyBody> = HandshakeError::UnsupportedVersion.into();
2018-02-27 10:09:24 -08:00
assert_eq!(resp.status(), StatusCode::BAD_REQUEST);
2021-06-17 17:57:58 +01:00
let resp: Response<AnyBody> = HandshakeError::BadWebsocketKey.into();
2018-02-27 10:09:24 -08:00
assert_eq!(resp.status(), StatusCode::BAD_REQUEST);
}
2017-10-22 17:33:24 -07:00
}