1
0
Fork 0
mirror of https://github.com/actix/actix-web.git synced 2024-06-11 09:49:29 +00:00
actix-web/src/ws/mod.rs

442 lines
16 KiB
Rust
Raw Normal View History

2017-10-08 05:41:02 +00:00
//! `WebSocket` support for Actix
//!
//! 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.
//!
//! ## Example
//!
//! ```rust
//! # extern crate actix;
//! # extern crate actix_web;
//! # use actix::*;
//! # use actix_web::*;
//! use actix_web::ws;
2017-10-08 05:41:02 +00:00
//!
2017-11-29 22:12:27 +00:00
//! // do websocket handshake and start actor
2018-01-01 01:26:32 +00:00
//! fn ws_index(req: HttpRequest) -> Result<HttpResponse> {
//! ws::start(req, Ws)
2017-11-29 18:31:24 +00:00
//! }
//!
//! struct Ws;
2017-10-08 05:41:02 +00:00
//!
//! impl Actor for Ws {
//! type Context = ws::WebsocketContext<Self>;
2017-10-08 05:41:02 +00:00
//! }
//!
2018-02-27 18:09:24 +00:00
//! // Handler for ws::Message messages
//! impl StreamHandler<ws::Message, ws::WsError> for Ws {
2018-01-05 21:30:21 +00:00
//!
//! fn handle(&mut self, msg: ws::Message, ctx: &mut Self::Context) {
2017-10-08 05:41:02 +00:00
//! match msg {
//! ws::Message::Ping(msg) => ctx.pong(&msg),
2018-02-10 06:26:48 +00:00
//! ws::Message::Text(text) => ctx.text(text),
//! ws::Message::Binary(bin) => ctx.binary(bin),
2017-10-08 05:41:02 +00:00
//! _ => (),
//! }
//! }
//! }
//! #
//! # fn main() {
//! # Application::new()
//! # .resource("/ws/", |r| r.f(ws_index)) // <- register websocket route
//! # .finish();
//! # }
2017-10-08 05:41:02 +00:00
//! ```
2018-02-26 21:58:23 +00:00
use bytes::Bytes;
use http::{Method, StatusCode, header};
2017-10-08 05:41:02 +00:00
use futures::{Async, Poll, Stream};
2018-02-26 21:58:23 +00:00
use byteorder::{ByteOrder, NetworkEndian};
2017-10-08 04:48:00 +00:00
2018-02-27 18:09:24 +00:00
use actix::{Actor, AsyncContext, StreamHandler};
2017-10-08 04:48:00 +00:00
use body::Binary;
2018-02-26 21:58:23 +00:00
use payload::PayloadHelper;
2018-02-27 18:09:24 +00:00
use error::{Error, PayloadError, ResponseError};
use httpmessage::HttpMessage;
use httprequest::HttpRequest;
2018-01-01 01:26:32 +00:00
use httpresponse::{ConnectionType, HttpResponse, HttpResponseBuilder};
2018-03-02 03:12:59 +00:00
use httpcodes::{HttpBadRequest, HttpMethodNotAllowed};
2017-10-08 04:48:00 +00:00
2018-01-10 19:13:29 +00:00
mod frame;
mod proto;
mod context;
mod mask;
mod client;
2018-01-10 19:13:29 +00:00
use self::frame::Frame;
use self::proto::{hash_key, OpCode};
pub use self::proto::CloseCode;
pub use self::context::WebsocketContext;
pub use self::client::{Client, ClientError,
ClientReader, ClientWriter, ClientHandshake};
#[allow(deprecated)]
2018-02-27 18:09:24 +00:00
pub use self::client::{WsClient, WsClientError,
WsClientReader, WsClientWriter, WsClientHandshake};
2018-01-28 06:03:03 +00:00
/// Backward compatibility
#[doc(hidden)]
#[deprecated(since="0.4.2", note="please use `ws::ProtocolError` instead")]
pub type WsError = ProtocolError;
#[doc(hidden)]
#[deprecated(since="0.4.2", note="please use `ws::HandshakeError` instead")]
pub type WsHandshakeError = HandshakeError;
2017-10-08 04:48:00 +00:00
2018-02-27 18:09:24 +00:00
/// Websocket errors
#[derive(Fail, Debug)]
pub enum ProtocolError {
2018-02-27 18:09:24 +00:00
/// Received an unmasked frame from client
#[fail(display="Received an unmasked frame from client")]
UnmaskedFrame,
/// Received a masked frame from server
#[fail(display="Received a masked frame from server")]
MaskedFrame,
/// Encountered invalid opcode
#[fail(display="Invalid opcode: {}", _0)]
InvalidOpcode(u8),
/// Invalid control frame length
#[fail(display="Invalid control frame length: {}", _0)]
InvalidLength(usize),
/// Bad web socket op code
#[fail(display="Bad web socket op code")]
BadOpCode,
/// A payload reached size limit.
#[fail(display="A payload reached size limit.")]
Overflow,
/// Continuation is not supproted
#[fail(display="Continuation is not supproted.")]
NoContinuation,
/// Bad utf-8 encoding
#[fail(display="Bad utf-8 encoding.")]
BadEncoding,
/// Payload error
#[fail(display="Payload error: {}", _0)]
Payload(#[cause] PayloadError),
}
impl ResponseError for ProtocolError {}
2018-02-27 18:09:24 +00:00
impl From<PayloadError> for ProtocolError {
fn from(err: PayloadError) -> ProtocolError {
ProtocolError::Payload(err)
2018-02-27 18:09:24 +00:00
}
}
/// Websocket handshake errors
#[derive(Fail, PartialEq, Debug)]
pub enum HandshakeError {
2018-02-27 18:09:24 +00:00
/// Only get method is allowed
#[fail(display="Method not allowed")]
GetMethodRequired,
/// Upgrade header if not set to websocket
#[fail(display="Websocket upgrade is expected")]
NoWebsocketUpgrade,
/// Connection header is not set to upgrade
#[fail(display="Connection upgrade is expected")]
NoConnectionUpgrade,
/// Websocket version header is not set
#[fail(display="Websocket version header is required")]
NoVersionHeader,
/// Unsupported websocket version
#[fail(display="Unsupported version")]
UnsupportedVersion,
/// Websocket key is not set or wrong
#[fail(display="Unknown websocket key")]
BadWebsocketKey,
}
impl ResponseError for HandshakeError {
2018-02-27 18:09:24 +00:00
fn error_response(&self) -> HttpResponse {
match *self {
HandshakeError::GetMethodRequired => {
2018-03-02 03:12:59 +00:00
HttpMethodNotAllowed
2018-02-27 18:09:24 +00:00
.build()
.header(header::ALLOW, "GET")
.finish()
.unwrap()
}
HandshakeError::NoWebsocketUpgrade =>
2018-03-02 03:12:59 +00:00
HttpBadRequest.with_reason("No WebSocket UPGRADE header found"),
HandshakeError::NoConnectionUpgrade =>
2018-03-02 03:12:59 +00:00
HttpBadRequest.with_reason("No CONNECTION upgrade"),
HandshakeError::NoVersionHeader =>
2018-03-02 03:12:59 +00:00
HttpBadRequest.with_reason("Websocket version header is required"),
HandshakeError::UnsupportedVersion =>
2018-03-02 03:12:59 +00:00
HttpBadRequest.with_reason("Unsupported version"),
HandshakeError::BadWebsocketKey =>
2018-03-02 03:12:59 +00:00
HttpBadRequest.with_reason("Handshake error"),
2018-02-27 18:09:24 +00:00
}
}
}
2017-10-08 06:59:57 +00:00
/// `WebSocket` Message
2018-02-12 20:17:30 +00:00
#[derive(Debug, PartialEq, Message)]
2017-10-08 04:48:00 +00:00
pub enum Message {
Text(String),
Binary(Binary),
2017-10-08 04:48:00 +00:00
Ping(String),
Pong(String),
2018-02-26 21:58:23 +00:00
Close(CloseCode),
2017-10-08 04:48:00 +00:00
}
2017-11-29 22:12:27 +00:00
/// Do websocket handshake and start actor
2018-02-25 08:21:45 +00:00
pub fn start<A, S>(req: HttpRequest<S>, actor: A) -> Result<HttpResponse, Error>
where A: Actor<Context=WebsocketContext<A, S>> + StreamHandler<Message, ProtocolError>,
2017-11-29 18:31:24 +00:00
S: 'static
{
2018-01-01 01:26:32 +00:00
let mut resp = handshake(&req)?;
let stream = WsStream::new(req.clone());
2018-01-01 01:26:32 +00:00
let mut ctx = WebsocketContext::new(req, actor);
2018-02-27 18:09:24 +00:00
ctx.add_stream(stream);
2018-01-01 01:26:32 +00:00
Ok(resp.body(ctx)?)
2017-11-29 18:31:24 +00:00
}
2017-10-08 05:41:02 +00:00
/// Prepare `WebSocket` handshake response.
2017-10-08 04:48:00 +00:00
///
2017-10-08 06:59:57 +00:00
/// This function returns handshake `HttpResponse`, ready to send to peer.
2017-10-08 05:41:02 +00:00
/// It does not perform any IO.
2017-10-08 04:48:00 +00:00
///
2017-10-08 05:41:02 +00: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.
pub fn handshake<S>(req: &HttpRequest<S>) -> Result<HttpResponseBuilder, HandshakeError> {
2017-10-08 04:48:00 +00:00
// WebSocket accepts only GET
if *req.method() != Method::GET {
return Err(HandshakeError::GetMethodRequired)
2017-10-08 04:48:00 +00:00
}
// Check for "UPGRADE" to websocket header
2017-10-10 06:07:32 +00: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 04:48:00 +00:00
} else {
false
};
if !has_hdr {
return Err(HandshakeError::NoWebsocketUpgrade)
2017-10-08 04:48:00 +00:00
}
// Upgrade connection
2017-10-14 07:11:12 +00:00
if !req.upgrade() {
return Err(HandshakeError::NoConnectionUpgrade)
2017-10-08 04:48:00 +00:00
}
// check supported version
2018-02-28 22:16:55 +00:00
if !req.headers().contains_key(header::SEC_WEBSOCKET_VERSION) {
return Err(HandshakeError::NoVersionHeader)
2017-10-08 04:48:00 +00:00
}
let supported_ver = {
2018-02-28 22:16:55 +00:00
if let Some(hdr) = req.headers().get(header::SEC_WEBSOCKET_VERSION) {
2017-10-10 06:07:32 +00:00
hdr == "13" || hdr == "8" || hdr == "7"
} else {
false
2017-10-08 04:48:00 +00:00
}
};
if !supported_ver {
return Err(HandshakeError::UnsupportedVersion)
2017-10-08 04:48:00 +00:00
}
// check client handshake for validity
2018-02-28 22:16:55 +00:00
if !req.headers().contains_key(header::SEC_WEBSOCKET_KEY) {
return Err(HandshakeError::BadWebsocketKey)
2017-10-10 06:07:32 +00:00
}
let key = {
2018-02-28 22:16:55 +00:00
let key = req.headers().get(header::SEC_WEBSOCKET_KEY).unwrap();
2017-10-10 06:07:32 +00:00
hash_key(key.as_ref())
2017-10-08 04:48:00 +00:00
};
2017-11-27 06:31:29 +00:00
Ok(HttpResponse::build(StatusCode::SWITCHING_PROTOCOLS)
2017-10-10 23:03:32 +00:00
.connection_type(ConnectionType::Upgrade)
.header(header::UPGRADE, "websocket")
.header(header::TRANSFER_ENCODING, "chunked")
2018-02-28 22:16:55 +00:00
.header(header::SEC_WEBSOCKET_ACCEPT, key.as_str())
2018-01-01 01:26:32 +00:00
.take())
2017-10-08 04:48:00 +00:00
}
2017-10-08 05:41:02 +00:00
/// Maps `Payload` stream into stream of `ws::Message` items
2018-02-26 21:58:23 +00:00
pub struct WsStream<S> {
rx: PayloadHelper<S>,
2017-10-13 23:33:23 +00:00
closed: bool,
2018-02-27 18:09:24 +00:00
max_size: usize,
2017-10-08 04:48:00 +00:00
}
2018-02-26 21:58:23 +00:00
impl<S> WsStream<S> where S: Stream<Item=Bytes, Error=PayloadError> {
2018-02-27 18:09:24 +00:00
/// Create new websocket frames stream
2018-02-26 21:58:23 +00:00
pub fn new(stream: S) -> WsStream<S> {
WsStream { rx: PayloadHelper::new(stream),
2018-02-27 18:09:24 +00:00
closed: false,
max_size: 65_536,
}
}
/// Set max frame size
///
/// By default max size is set to 64kb
pub fn max_size(mut self, size: usize) -> Self {
self.max_size = size;
self
2017-10-08 04:48:00 +00:00
}
}
2018-02-26 21:58:23 +00:00
impl<S> Stream for WsStream<S> where S: Stream<Item=Bytes, Error=PayloadError> {
2017-10-08 04:48:00 +00:00
type Item = Message;
type Error = ProtocolError;
2017-10-08 04:48:00 +00:00
fn poll(&mut self) -> Poll<Option<Self::Item>, Self::Error> {
2018-02-26 21:58:23 +00:00
if self.closed {
return Ok(Async::Ready(None))
2017-10-09 03:16:48 +00:00
}
2017-10-08 04:48:00 +00:00
2018-02-27 18:09:24 +00:00
match Frame::parse(&mut self.rx, true, self.max_size) {
2018-02-26 21:58:23 +00:00
Ok(Async::Ready(Some(frame))) => {
2018-02-27 18:09:24 +00:00
let (finished, opcode, payload) = frame.unpack();
// continuation is not supported
if !finished {
self.closed = true;
return Err(ProtocolError::NoContinuation)
2018-02-27 18:09:24 +00:00
}
2017-10-08 04:48:00 +00:00
2018-02-26 21:58:23 +00:00
match opcode {
2018-03-09 01:19:50 +00:00
OpCode::Continue => Err(ProtocolError::NoContinuation),
2018-02-27 18:09:24 +00:00
OpCode::Bad => {
self.closed = true;
Err(ProtocolError::BadOpCode)
2018-02-27 18:09:24 +00:00
}
2018-02-26 21:58:23 +00:00
OpCode::Close => {
self.closed = true;
let code = NetworkEndian::read_uint(payload.as_ref(), 2) as u16;
Ok(Async::Ready(
Some(Message::Close(CloseCode::from(code)))))
},
OpCode::Ping =>
Ok(Async::Ready(Some(
Message::Ping(
String::from_utf8_lossy(payload.as_ref()).into())))),
OpCode::Pong =>
Ok(Async::Ready(Some(
Message::Pong(String::from_utf8_lossy(payload.as_ref()).into())))),
OpCode::Binary =>
Ok(Async::Ready(Some(Message::Binary(payload)))),
OpCode::Text => {
let tmp = Vec::from(payload.as_ref());
match String::from_utf8(tmp) {
Ok(s) =>
Ok(Async::Ready(Some(Message::Text(s)))),
2018-02-27 18:09:24 +00:00
Err(_) => {
self.closed = true;
Err(ProtocolError::BadEncoding)
2018-02-27 18:09:24 +00:00
}
2017-10-13 23:33:23 +00:00
}
}
}
2017-10-08 04:48:00 +00:00
}
2018-02-26 21:58:23 +00:00
Ok(Async::Ready(None)) => Ok(Async::Ready(None)),
Ok(Async::NotReady) => Ok(Async::NotReady),
2018-02-27 18:09:24 +00:00
Err(e) => {
2018-02-26 21:58:23 +00:00
self.closed = true;
2018-02-27 18:09:24 +00:00
Err(e)
2018-02-26 21:58:23 +00:00
}
2017-10-08 04:48:00 +00:00
}
}
}
2017-10-23 00:33:24 +00:00
#[cfg(test)]
mod tests {
2017-11-16 06:06:28 +00:00
use super::*;
2017-12-01 03:01:25 +00:00
use std::str::FromStr;
use http::{Method, HeaderMap, Version, Uri, header};
2017-10-23 00:33:24 +00:00
#[test]
fn test_handshake() {
2017-12-01 03:01:25 +00:00
let req = HttpRequest::new(Method::POST, Uri::from_str("/").unwrap(),
2017-12-13 16:00:25 +00:00
Version::HTTP_11, HeaderMap::new(), None);
assert_eq!(HandshakeError::GetMethodRequired, handshake(&req).err().unwrap());
2017-10-23 00:33:24 +00:00
2017-12-01 03:01:25 +00:00
let req = HttpRequest::new(Method::GET, Uri::from_str("/").unwrap(),
2017-12-13 16:00:25 +00:00
Version::HTTP_11, HeaderMap::new(), None);
assert_eq!(HandshakeError::NoWebsocketUpgrade, handshake(&req).err().unwrap());
2017-10-23 00:33:24 +00:00
let mut headers = HeaderMap::new();
headers.insert(header::UPGRADE,
header::HeaderValue::from_static("test"));
2017-12-01 03:01:25 +00:00
let req = HttpRequest::new(Method::GET, Uri::from_str("/").unwrap(),
2017-12-13 16:00:25 +00:00
Version::HTTP_11, headers, None);
assert_eq!(HandshakeError::NoWebsocketUpgrade, handshake(&req).err().unwrap());
2017-10-23 00:33:24 +00:00
let mut headers = HeaderMap::new();
headers.insert(header::UPGRADE,
header::HeaderValue::from_static("websocket"));
2017-12-01 03:01:25 +00:00
let req = HttpRequest::new(Method::GET, Uri::from_str("/").unwrap(),
2017-12-13 16:00:25 +00:00
Version::HTTP_11, headers, None);
assert_eq!(HandshakeError::NoConnectionUpgrade, handshake(&req).err().unwrap());
2017-10-23 00:33:24 +00:00
let mut headers = HeaderMap::new();
headers.insert(header::UPGRADE,
header::HeaderValue::from_static("websocket"));
headers.insert(header::CONNECTION,
header::HeaderValue::from_static("upgrade"));
2017-12-01 03:01:25 +00:00
let req = HttpRequest::new(Method::GET, Uri::from_str("/").unwrap(),
2017-12-13 16:00:25 +00:00
Version::HTTP_11, headers, None);
assert_eq!(HandshakeError::NoVersionHeader, handshake(&req).err().unwrap());
2017-10-23 00:33:24 +00:00
let mut headers = HeaderMap::new();
headers.insert(header::UPGRADE,
header::HeaderValue::from_static("websocket"));
headers.insert(header::CONNECTION,
header::HeaderValue::from_static("upgrade"));
2018-02-28 22:16:55 +00:00
headers.insert(header::SEC_WEBSOCKET_VERSION,
2017-10-23 00:33:24 +00:00
header::HeaderValue::from_static("5"));
2017-12-01 03:01:25 +00:00
let req = HttpRequest::new(Method::GET, Uri::from_str("/").unwrap(),
2017-12-13 16:00:25 +00:00
Version::HTTP_11, headers, None);
assert_eq!(HandshakeError::UnsupportedVersion, handshake(&req).err().unwrap());
2017-10-23 00:33:24 +00:00
let mut headers = HeaderMap::new();
headers.insert(header::UPGRADE,
header::HeaderValue::from_static("websocket"));
headers.insert(header::CONNECTION,
header::HeaderValue::from_static("upgrade"));
2018-02-28 22:16:55 +00:00
headers.insert(header::SEC_WEBSOCKET_VERSION,
2017-10-23 00:33:24 +00:00
header::HeaderValue::from_static("13"));
2017-12-01 03:01:25 +00:00
let req = HttpRequest::new(Method::GET, Uri::from_str("/").unwrap(),
2017-12-13 16:00:25 +00:00
Version::HTTP_11, headers, None);
assert_eq!(HandshakeError::BadWebsocketKey, handshake(&req).err().unwrap());
2017-10-23 00:33:24 +00:00
let mut headers = HeaderMap::new();
headers.insert(header::UPGRADE,
header::HeaderValue::from_static("websocket"));
headers.insert(header::CONNECTION,
header::HeaderValue::from_static("upgrade"));
2018-02-28 22:16:55 +00:00
headers.insert(header::SEC_WEBSOCKET_VERSION,
2017-10-23 00:33:24 +00:00
header::HeaderValue::from_static("13"));
2018-02-28 22:16:55 +00:00
headers.insert(header::SEC_WEBSOCKET_KEY,
2017-10-23 00:33:24 +00:00
header::HeaderValue::from_static("13"));
2017-12-01 03:01:25 +00:00
let req = HttpRequest::new(Method::GET, Uri::from_str("/").unwrap(),
2017-12-13 16:00:25 +00:00
Version::HTTP_11, headers, None);
2018-01-01 01:26:32 +00:00
assert_eq!(StatusCode::SWITCHING_PROTOCOLS,
handshake(&req).unwrap().finish().unwrap().status());
2017-10-23 00:33:24 +00:00
}
2018-02-27 18:09:24 +00:00
#[test]
fn test_wserror_http_response() {
let resp: HttpResponse = HandshakeError::GetMethodRequired.error_response();
2018-02-27 18:09:24 +00:00
assert_eq!(resp.status(), StatusCode::METHOD_NOT_ALLOWED);
let resp: HttpResponse = HandshakeError::NoWebsocketUpgrade.error_response();
2018-02-27 18:09:24 +00:00
assert_eq!(resp.status(), StatusCode::BAD_REQUEST);
let resp: HttpResponse = HandshakeError::NoConnectionUpgrade.error_response();
2018-02-27 18:09:24 +00:00
assert_eq!(resp.status(), StatusCode::BAD_REQUEST);
let resp: HttpResponse = HandshakeError::NoVersionHeader.error_response();
2018-02-27 18:09:24 +00:00
assert_eq!(resp.status(), StatusCode::BAD_REQUEST);
let resp: HttpResponse = HandshakeError::UnsupportedVersion.error_response();
2018-02-27 18:09:24 +00:00
assert_eq!(resp.status(), StatusCode::BAD_REQUEST);
let resp: HttpResponse = HandshakeError::BadWebsocketKey.error_response();
2018-02-27 18:09:24 +00:00
assert_eq!(resp.status(), StatusCode::BAD_REQUEST);
}
2017-10-23 00:33:24 +00:00
}