1
0
mirror of https://github.com/fafhrd91/actix-web synced 2024-11-25 08:52:42 +01:00
actix-web/src/ws/mod.rs

296 lines
9.7 KiB
Rust
Raw Normal View History

2018-10-05 21:47:22 +02:00
//! WebSocket protocol support.
2017-10-08 07:41:02 +02:00
//!
2018-04-14 01:02:01 +02:00
//! To setup a `WebSocket`, first do web socket handshake then on success
//! convert `Payload` into a `WsStream` stream and then use `WsWriter` to
//! communicate with the peer.
2018-10-05 21:47:22 +02:00
use std::io;
2017-10-08 06:48:00 +02:00
2018-10-05 21:47:22 +02:00
use error::ResponseError;
use http::{header, Method, StatusCode};
2018-10-05 19:19:15 +02:00
use request::Request;
2018-10-05 20:04:59 +02:00
use response::{ConnectionType, Response, ResponseBuilder};
2017-10-08 06:48:00 +02:00
2018-10-05 21:47:22 +02:00
mod codec;
2018-04-14 01:02:01 +02:00
mod frame;
mod mask;
2018-04-14 01:02:01 +02:00
mod proto;
2018-10-05 23:30:40 +02:00
mod transport;
2018-01-10 20:13:29 +01:00
2018-10-10 22:20:00 +02:00
pub use self::codec::{Codec, Frame, Message};
pub use self::frame::Parser;
pub use self::proto::{CloseCode, CloseReason, OpCode};
2018-10-05 23:30:40 +02:00
pub use self::transport::Transport;
/// Websocket protocol errors
2018-02-27 19:09:24 +01:00
#[derive(Fail, Debug)]
pub enum ProtocolError {
2018-02-27 19:09:24 +01:00
/// Received an unmasked frame from client
2018-04-14 01:02:01 +02:00
#[fail(display = "Received an unmasked frame from client")]
2018-02-27 19:09:24 +01:00
UnmaskedFrame,
/// Received a masked frame from server
2018-04-14 01:02:01 +02:00
#[fail(display = "Received a masked frame from server")]
2018-02-27 19:09:24 +01:00
MaskedFrame,
/// Encountered invalid opcode
2018-04-14 01:02:01 +02:00
#[fail(display = "Invalid opcode: {}", _0)]
2018-02-27 19:09:24 +01:00
InvalidOpcode(u8),
/// Invalid control frame length
2018-04-14 01:02:01 +02:00
#[fail(display = "Invalid control frame length: {}", _0)]
2018-02-27 19:09:24 +01:00
InvalidLength(usize),
/// Bad web socket op code
2018-04-14 01:02:01 +02:00
#[fail(display = "Bad web socket op code")]
2018-02-27 19:09:24 +01:00
BadOpCode,
/// A payload reached size limit.
2018-04-14 01:02:01 +02:00
#[fail(display = "A payload reached size limit.")]
2018-02-27 19:09:24 +01:00
Overflow,
2018-03-24 07:35:52 +01:00
/// Continuation is not supported
2018-04-14 01:02:01 +02:00
#[fail(display = "Continuation is not supported.")]
2018-02-27 19:09:24 +01:00
NoContinuation,
/// Bad utf-8 encoding
2018-04-14 01:02:01 +02:00
#[fail(display = "Bad utf-8 encoding.")]
2018-02-27 19:09:24 +01:00
BadEncoding,
2018-10-05 21:47:22 +02:00
/// Io error
#[fail(display = "io error: {}", _0)]
Io(#[cause] io::Error),
2018-02-27 19:09:24 +01:00
}
impl ResponseError for ProtocolError {}
2018-02-27 19:09:24 +01:00
2018-10-05 21:47:22 +02:00
impl From<io::Error> for ProtocolError {
fn from(err: io::Error) -> ProtocolError {
ProtocolError::Io(err)
2018-02-27 19:09:24 +01:00
}
}
/// Websocket handshake errors
#[derive(Fail, PartialEq, Debug)]
pub enum HandshakeError {
2018-02-27 19:09:24 +01:00
/// Only get method is allowed
2018-04-14 01:02:01 +02:00
#[fail(display = "Method not allowed")]
2018-02-27 19:09:24 +01:00
GetMethodRequired,
/// Upgrade header if not set to websocket
2018-04-14 01:02:01 +02:00
#[fail(display = "Websocket upgrade is expected")]
2018-02-27 19:09:24 +01:00
NoWebsocketUpgrade,
/// Connection header is not set to upgrade
2018-04-14 01:02:01 +02:00
#[fail(display = "Connection upgrade is expected")]
2018-02-27 19:09:24 +01:00
NoConnectionUpgrade,
/// Websocket version header is not set
2018-04-14 01:02:01 +02:00
#[fail(display = "Websocket version header is required")]
2018-02-27 19:09:24 +01:00
NoVersionHeader,
/// Unsupported websocket version
2018-04-14 01:02:01 +02:00
#[fail(display = "Unsupported version")]
2018-02-27 19:09:24 +01:00
UnsupportedVersion,
/// Websocket key is not set or wrong
2018-04-14 01:02:01 +02:00
#[fail(display = "Unknown websocket key")]
2018-02-27 19:09:24 +01:00
BadWebsocketKey,
}
impl ResponseError for HandshakeError {
2018-10-05 20:04:59 +02:00
fn error_response(&self) -> Response {
2018-02-27 19:09:24 +01:00
match *self {
2018-10-05 20:04:59 +02:00
HandshakeError::GetMethodRequired => Response::MethodNotAllowed()
2018-04-29 18:09:08 +02:00
.header(header::ALLOW, "GET")
.finish(),
2018-10-05 20:04:59 +02:00
HandshakeError::NoWebsocketUpgrade => Response::BadRequest()
2018-04-14 01:02:01 +02:00
.reason("No WebSocket UPGRADE header found")
.finish(),
2018-10-05 20:04:59 +02:00
HandshakeError::NoConnectionUpgrade => Response::BadRequest()
2018-04-29 18:09:08 +02:00
.reason("No CONNECTION upgrade")
.finish(),
2018-10-05 20:04:59 +02:00
HandshakeError::NoVersionHeader => Response::BadRequest()
2018-04-14 01:02:01 +02:00
.reason("Websocket version header is required")
.finish(),
2018-10-05 20:04:59 +02:00
HandshakeError::UnsupportedVersion => Response::BadRequest()
2018-04-29 18:09:08 +02:00
.reason("Unsupported version")
.finish(),
2018-10-05 20:04:59 +02:00
HandshakeError::BadWebsocketKey => {
Response::BadRequest().reason("Handshake error").finish()
}
2018-02-27 19:09:24 +01:00
}
}
}
2017-10-08 07:41:02 +02:00
/// Prepare `WebSocket` handshake response.
2017-10-08 06:48:00 +02:00
///
2018-10-05 20:04:59 +02:00
/// This function returns handshake `Response`, ready to send to peer.
2017-10-08 07:41:02 +02:00
/// It does not perform any IO.
2017-10-08 06:48:00 +02:00
///
2017-10-08 07:41:02 +02:00
// /// `protocols` is a sequence of known protocols. On successful handshake,
// /// the returned response headers contain the first protocol in this list
// /// which the server also knows.
2018-10-05 20:04:59 +02:00
pub fn handshake(req: &Request) -> Result<ResponseBuilder, HandshakeError> {
2017-10-08 06:48:00 +02:00
// WebSocket accepts only GET
if *req.method() != Method::GET {
2018-04-14 01:02:01 +02:00
return Err(HandshakeError::GetMethodRequired);
2017-10-08 06:48:00 +02:00
}
// Check for "UPGRADE" to websocket header
2017-10-10 08:07:32 +02:00
let has_hdr = if let Some(hdr) = req.headers().get(header::UPGRADE) {
if let Ok(s) = hdr.to_str() {
s.to_lowercase().contains("websocket")
} else {
false
}
2017-10-08 06:48:00 +02:00
} else {
false
};
if !has_hdr {
2018-04-14 01:02:01 +02:00
return Err(HandshakeError::NoWebsocketUpgrade);
2017-10-08 06:48:00 +02:00
}
// Upgrade connection
2017-10-14 09:11:12 +02:00
if !req.upgrade() {
2018-04-14 01:02:01 +02:00
return Err(HandshakeError::NoConnectionUpgrade);
2017-10-08 06:48:00 +02:00
}
// check supported version
2018-05-17 21:20:20 +02:00
if !req.headers().contains_key(header::SEC_WEBSOCKET_VERSION) {
2018-04-14 01:02:01 +02:00
return Err(HandshakeError::NoVersionHeader);
2017-10-08 06:48:00 +02:00
}
let supported_ver = {
2018-02-28 23:16:55 +01:00
if let Some(hdr) = req.headers().get(header::SEC_WEBSOCKET_VERSION) {
2017-10-10 08:07:32 +02:00
hdr == "13" || hdr == "8" || hdr == "7"
} else {
false
2017-10-08 06:48:00 +02:00
}
};
if !supported_ver {
2018-04-14 01:02:01 +02:00
return Err(HandshakeError::UnsupportedVersion);
2017-10-08 06:48:00 +02:00
}
// check client handshake for validity
2018-02-28 23:16:55 +01:00
if !req.headers().contains_key(header::SEC_WEBSOCKET_KEY) {
2018-04-14 01:02:01 +02:00
return Err(HandshakeError::BadWebsocketKey);
2017-10-10 08:07:32 +02:00
}
let key = {
2018-02-28 23:16:55 +01:00
let key = req.headers().get(header::SEC_WEBSOCKET_KEY).unwrap();
2018-03-09 22:03:15 +01:00
proto::hash_key(key.as_ref())
2017-10-08 06:48:00 +02:00
};
2018-10-05 20:04:59 +02:00
Ok(Response::build(StatusCode::SWITCHING_PROTOCOLS)
2018-04-14 01:02:01 +02:00
.connection_type(ConnectionType::Upgrade)
.header(header::UPGRADE, "websocket")
.header(header::TRANSFER_ENCODING, "chunked")
.header(header::SEC_WEBSOCKET_ACCEPT, key.as_str())
.take())
2017-10-08 06:48:00 +02:00
}
2017-10-23 02:33:24 +02:00
#[cfg(test)]
mod tests {
2017-11-16 07:06:28 +01:00
use super::*;
2018-07-04 17:01:27 +02:00
use http::{header, Method};
2018-06-25 06:58:04 +02:00
use test::TestRequest;
2017-10-23 02:33:24 +02:00
#[test]
fn test_handshake() {
2018-06-25 06:58:04 +02:00
let req = TestRequest::default().method(Method::POST).finish();
2018-04-29 18:09:08 +02:00
assert_eq!(
HandshakeError::GetMethodRequired,
handshake(&req).err().unwrap()
);
2018-04-14 01:02:01 +02:00
2018-06-25 06:58:04 +02:00
let req = TestRequest::default().finish();
2018-04-29 18:09:08 +02:00
assert_eq!(
HandshakeError::NoWebsocketUpgrade,
handshake(&req).err().unwrap()
);
2017-10-23 02:33:24 +02:00
2018-06-25 06:58:04 +02:00
let req = TestRequest::default()
.header(header::UPGRADE, header::HeaderValue::from_static("test"))
.finish();
2018-04-29 18:09:08 +02:00
assert_eq!(
HandshakeError::NoWebsocketUpgrade,
handshake(&req).err().unwrap()
);
2017-10-23 02:33:24 +02:00
2018-06-25 06:58:04 +02:00
let req = TestRequest::default()
.header(
header::UPGRADE,
header::HeaderValue::from_static("websocket"),
2018-08-23 18:48:01 +02:00
).finish();
2018-04-29 18:09:08 +02:00
assert_eq!(
HandshakeError::NoConnectionUpgrade,
handshake(&req).err().unwrap()
);
2017-10-23 02:33:24 +02:00
2018-06-25 06:58:04 +02:00
let req = TestRequest::default()
.header(
header::UPGRADE,
header::HeaderValue::from_static("websocket"),
2018-08-23 18:48:01 +02:00
).header(
2018-06-25 06:58:04 +02:00
header::CONNECTION,
header::HeaderValue::from_static("upgrade"),
2018-08-23 18:48:01 +02:00
).finish();
2018-04-29 18:09:08 +02:00
assert_eq!(
HandshakeError::NoVersionHeader,
handshake(&req).err().unwrap()
);
2017-10-23 02:33:24 +02:00
2018-06-25 06:58:04 +02:00
let req = TestRequest::default()
.header(
header::UPGRADE,
header::HeaderValue::from_static("websocket"),
2018-08-23 18:48:01 +02:00
).header(
2018-06-25 06:58:04 +02:00
header::CONNECTION,
header::HeaderValue::from_static("upgrade"),
2018-08-23 18:48:01 +02:00
).header(
2018-06-25 06:58:04 +02:00
header::SEC_WEBSOCKET_VERSION,
header::HeaderValue::from_static("5"),
2018-08-23 18:48:01 +02:00
).finish();
2018-04-29 18:09:08 +02:00
assert_eq!(
HandshakeError::UnsupportedVersion,
handshake(&req).err().unwrap()
);
2017-10-23 02:33:24 +02:00
2018-06-25 06:58:04 +02:00
let req = TestRequest::default()
.header(
header::UPGRADE,
header::HeaderValue::from_static("websocket"),
2018-08-23 18:48:01 +02:00
).header(
2018-06-25 06:58:04 +02:00
header::CONNECTION,
header::HeaderValue::from_static("upgrade"),
2018-08-23 18:48:01 +02:00
).header(
2018-06-25 06:58:04 +02:00
header::SEC_WEBSOCKET_VERSION,
header::HeaderValue::from_static("13"),
2018-08-23 18:48:01 +02:00
).finish();
2018-04-29 18:09:08 +02:00
assert_eq!(
HandshakeError::BadWebsocketKey,
handshake(&req).err().unwrap()
);
2017-10-23 02:33:24 +02:00
2018-06-25 06:58:04 +02:00
let req = TestRequest::default()
.header(
header::UPGRADE,
header::HeaderValue::from_static("websocket"),
2018-08-23 18:48:01 +02:00
).header(
2018-06-25 06:58:04 +02:00
header::CONNECTION,
header::HeaderValue::from_static("upgrade"),
2018-08-23 18:48:01 +02:00
).header(
2018-06-25 06:58:04 +02:00
header::SEC_WEBSOCKET_VERSION,
header::HeaderValue::from_static("13"),
2018-08-23 18:48:01 +02:00
).header(
2018-06-25 06:58:04 +02:00
header::SEC_WEBSOCKET_KEY,
header::HeaderValue::from_static("13"),
2018-08-23 18:48:01 +02:00
).finish();
2018-04-14 01:02:01 +02:00
assert_eq!(
StatusCode::SWITCHING_PROTOCOLS,
handshake(&req).unwrap().finish().status()
);
2017-10-23 02:33:24 +02:00
}
2018-02-27 19:09:24 +01:00
#[test]
fn test_wserror_http_response() {
2018-10-05 20:04:59 +02:00
let resp: Response = HandshakeError::GetMethodRequired.error_response();
2018-02-27 19:09:24 +01:00
assert_eq!(resp.status(), StatusCode::METHOD_NOT_ALLOWED);
2018-10-05 20:04:59 +02:00
let resp: Response = HandshakeError::NoWebsocketUpgrade.error_response();
2018-02-27 19:09:24 +01:00
assert_eq!(resp.status(), StatusCode::BAD_REQUEST);
2018-10-05 20:04:59 +02:00
let resp: Response = HandshakeError::NoConnectionUpgrade.error_response();
2018-02-27 19:09:24 +01:00
assert_eq!(resp.status(), StatusCode::BAD_REQUEST);
2018-10-05 20:04:59 +02:00
let resp: Response = HandshakeError::NoVersionHeader.error_response();
2018-02-27 19:09:24 +01:00
assert_eq!(resp.status(), StatusCode::BAD_REQUEST);
2018-10-05 20:04:59 +02:00
let resp: Response = HandshakeError::UnsupportedVersion.error_response();
2018-02-27 19:09:24 +01:00
assert_eq!(resp.status(), StatusCode::BAD_REQUEST);
2018-10-05 20:04:59 +02:00
let resp: Response = HandshakeError::BadWebsocketKey.error_response();
2018-02-27 19:09:24 +01:00
assert_eq!(resp.status(), StatusCode::BAD_REQUEST);
}
2017-10-23 02:33:24 +02:00
}