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

349 lines
12 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
//! }
//!
//! // Define Handler for ws::Message message
//! impl Handler<ws::Message> for Ws {
2018-01-05 21:30:21 +00:00
//! type Result = ();
//!
//! 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),
//! 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
//! ```
2017-10-24 06:39:01 +00:00
use bytes::BytesMut;
use http::{Method, StatusCode, header};
2017-10-08 05:41:02 +00:00
use futures::{Async, Poll, Stream};
2017-10-08 04:48:00 +00:00
2018-01-06 09:06:35 +00:00
use actix::{Actor, AsyncContext, ResponseType, Handler};
2017-10-08 04:48:00 +00:00
use body::Binary;
2017-12-19 08:18:57 +00:00
use payload::ReadAny;
2017-11-29 18:31:24 +00:00
use error::{Error, WsHandshakeError};
use httprequest::HttpRequest;
2018-01-01 01:26:32 +00:00
use httpresponse::{ConnectionType, HttpResponse, HttpResponseBuilder};
2017-10-08 04:48:00 +00:00
2018-01-10 19:13:29 +00:00
mod frame;
mod proto;
mod context;
use ws::frame::Frame;
use ws::proto::{hash_key, OpCode};
pub use ws::proto::CloseCode;
pub use ws::context::WebsocketContext;
2017-10-08 04:48:00 +00:00
const SEC_WEBSOCKET_ACCEPT: &str = "SEC-WEBSOCKET-ACCEPT";
const SEC_WEBSOCKET_KEY: &str = "SEC-WEBSOCKET-KEY";
const SEC_WEBSOCKET_VERSION: &str = "SEC-WEBSOCKET-VERSION";
2017-10-10 06:07:32 +00:00
// const SEC_WEBSOCKET_PROTOCOL: &'static str = "SEC-WEBSOCKET-PROTOCOL";
2017-10-08 04:48:00 +00:00
2017-10-08 06:59:57 +00:00
/// `WebSocket` Message
2017-10-08 04:48:00 +00:00
#[derive(Debug)]
pub enum Message {
Text(String),
Binary(Binary),
2017-10-08 04:48:00 +00:00
Ping(String),
Pong(String),
Close,
Closed,
Error
}
2017-10-21 22:21:16 +00:00
impl ResponseType for Message {
type Item = ();
type Error = ();
}
2017-11-29 22:12:27 +00:00
/// Do websocket handshake and start actor
2018-01-01 01:26:32 +00:00
pub fn start<A, S>(mut req: HttpRequest<S>, actor: A) -> Result<HttpResponse, Error>
where A: Actor<Context=WebsocketContext<A, S>> + Handler<Message>,
2017-11-29 18:31:24 +00:00
S: 'static
{
2018-01-01 01:26:32 +00:00
let mut resp = handshake(&req)?;
2017-12-19 08:18:57 +00:00
let stream = WsStream::new(req.payload_mut().readany());
2018-01-01 01:26:32 +00:00
let mut ctx = WebsocketContext::new(req, actor);
2018-01-05 21:30:21 +00:00
ctx.add_message_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.
2018-01-01 01:26:32 +00:00
pub fn handshake<S>(req: &HttpRequest<S>) -> Result<HttpResponseBuilder, WsHandshakeError> {
2017-10-08 04:48:00 +00:00
// WebSocket accepts only GET
if *req.method() != Method::GET {
2017-11-16 06:06:28 +00:00
return Err(WsHandshakeError::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 {
2017-11-16 06:06:28 +00:00
return Err(WsHandshakeError::NoWebsocketUpgrade)
2017-10-08 04:48:00 +00:00
}
// Upgrade connection
2017-10-14 07:11:12 +00:00
if !req.upgrade() {
2017-11-16 06:06:28 +00:00
return Err(WsHandshakeError::NoConnectionUpgrade)
2017-10-08 04:48:00 +00:00
}
// check supported version
2017-10-10 06:07:32 +00:00
if !req.headers().contains_key(SEC_WEBSOCKET_VERSION) {
2017-11-16 06:06:28 +00:00
return Err(WsHandshakeError::NoVersionHeader)
2017-10-08 04:48:00 +00:00
}
let supported_ver = {
2017-10-10 06:07:32 +00:00
if let Some(hdr) = req.headers().get(SEC_WEBSOCKET_VERSION) {
hdr == "13" || hdr == "8" || hdr == "7"
} else {
false
2017-10-08 04:48:00 +00:00
}
};
if !supported_ver {
2017-11-16 06:06:28 +00:00
return Err(WsHandshakeError::UnsupportedVersion)
2017-10-08 04:48:00 +00:00
}
// check client handshake for validity
2017-10-10 06:07:32 +00:00
if !req.headers().contains_key(SEC_WEBSOCKET_KEY) {
2017-11-16 06:06:28 +00:00
return Err(WsHandshakeError::BadWebsocketKey)
2017-10-10 06:07:32 +00:00
}
let key = {
let key = req.headers().get(SEC_WEBSOCKET_KEY).unwrap();
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")
.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
2017-10-08 04:48:00 +00:00
pub struct WsStream {
2017-12-19 08:18:57 +00:00
rx: ReadAny,
2017-10-08 04:48:00 +00:00
buf: BytesMut,
2017-10-13 23:33:23 +00:00
closed: bool,
error_sent: bool,
2017-10-08 04:48:00 +00:00
}
impl WsStream {
2017-12-19 08:18:57 +00:00
pub fn new(payload: ReadAny) -> WsStream {
2017-12-13 05:32:58 +00:00
WsStream { rx: payload,
buf: BytesMut::new(),
closed: false,
error_sent: false }
2017-10-08 04:48:00 +00:00
}
}
impl Stream for WsStream {
type Item = Message;
type Error = ();
fn poll(&mut self) -> Poll<Option<Self::Item>, Self::Error> {
let mut done = false;
2017-10-13 23:33:23 +00:00
if !self.closed {
loop {
2017-12-19 08:18:57 +00:00
match self.rx.poll() {
2017-10-27 06:14:33 +00:00
Ok(Async::Ready(Some(chunk))) => {
2017-12-19 08:18:57 +00:00
self.buf.extend_from_slice(&chunk)
2017-10-13 23:33:23 +00:00
}
2017-10-27 06:14:33 +00:00
Ok(Async::Ready(None)) => {
done = true;
2017-10-13 23:33:23 +00:00
self.closed = true;
2017-10-21 06:12:36 +00:00
break;
2017-10-13 23:33:23 +00:00
}
2017-10-27 06:14:33 +00:00
Ok(Async::NotReady) => break,
Err(_) => {
2017-10-21 06:12:36 +00:00
self.closed = true;
break;
2017-10-13 23:33:23 +00:00
}
2017-10-09 03:16:48 +00:00
}
2017-10-08 04:48:00 +00:00
}
2017-10-09 03:16:48 +00:00
}
2017-10-08 04:48:00 +00:00
2017-10-09 03:16:48 +00:00
loop {
2018-01-10 19:13:29 +00:00
match Frame::parse(&mut self.buf) {
2017-10-08 04:48:00 +00:00
Ok(Some(frame)) => {
2017-12-16 15:29:15 +00:00
// trace!("WsFrame {}", frame);
2017-10-08 05:41:02 +00:00
let (_finished, opcode, payload) = frame.unpack();
2017-10-08 04:48:00 +00:00
match opcode {
OpCode::Continue => continue,
OpCode::Bad =>
return Ok(Async::Ready(Some(Message::Error))),
2017-10-21 06:12:36 +00:00
OpCode::Close => {
self.closed = true;
self.error_sent = true;
return Ok(Async::Ready(Some(Message::Closed)))
},
2017-10-08 04:48:00 +00:00
OpCode::Ping =>
return Ok(Async::Ready(Some(
Message::Ping(
String::from_utf8_lossy(payload.as_ref()).into())))),
2017-10-08 04:48:00 +00:00
OpCode::Pong =>
return Ok(Async::Ready(Some(
Message::Pong(
String::from_utf8_lossy(payload.as_ref()).into())))),
2017-10-08 04:48:00 +00:00
OpCode::Binary =>
return Ok(Async::Ready(Some(Message::Binary(payload)))),
OpCode::Text => {
let tmp = Vec::from(payload.as_ref());
match String::from_utf8(tmp) {
2017-10-08 04:48:00 +00:00
Ok(s) =>
return Ok(Async::Ready(Some(Message::Text(s)))),
2017-10-08 05:41:02 +00:00
Err(_) =>
2017-10-08 04:48:00 +00:00
return Ok(Async::Ready(Some(Message::Error))),
}
}
}
}
2017-10-13 23:33:23 +00:00
Ok(None) => {
if done {
return Ok(Async::Ready(None))
} else if self.closed {
if !self.error_sent {
self.error_sent = true;
return Ok(Async::Ready(Some(Message::Closed)))
} else {
return Ok(Async::Ready(None))
}
} else {
return Ok(Async::NotReady)
}
2017-10-08 04:48:00 +00:00
},
2017-10-13 23:33:23 +00:00
Err(_) => {
self.closed = true;
self.error_sent = true;
return Ok(Async::Ready(Some(Message::Error)));
}
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);
2017-11-16 06:06:28 +00:00
assert_eq!(WsHandshakeError::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);
2017-11-16 06:28:02 +00:00
assert_eq!(WsHandshakeError::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);
2017-11-16 06:28:02 +00:00
assert_eq!(WsHandshakeError::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);
2017-11-16 06:28:02 +00:00
assert_eq!(WsHandshakeError::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);
2017-11-16 06:28:02 +00:00
assert_eq!(WsHandshakeError::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"));
headers.insert(SEC_WEBSOCKET_VERSION,
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);
2017-11-16 06:28:02 +00:00
assert_eq!(WsHandshakeError::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"));
headers.insert(SEC_WEBSOCKET_VERSION,
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);
2017-11-16 06:28:02 +00:00
assert_eq!(WsHandshakeError::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"));
headers.insert(SEC_WEBSOCKET_VERSION,
header::HeaderValue::from_static("13"));
headers.insert(SEC_WEBSOCKET_KEY,
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
}
}