forked from kpcyrd/sn0int
-
Notifications
You must be signed in to change notification settings - Fork 0
/
websockets.rs
167 lines (146 loc) · 4.8 KB
/
websockets.rs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
use crate::errors::*;
use crate::hlua::AnyLuaValue;
use crate::json::LuaJsonValue;
use crate::sockets::{SocketOptions, Stream};
use chrootable_https::DnsResolver;
use http::Request;
use serde::Deserialize;
use std::collections::HashMap;
use std::io;
use std::net::SocketAddr;
use tungstenite::protocol::{self, Message};
use url::Url;
#[derive(Debug, Default, Deserialize)]
pub struct WebSocketOptions {
pub headers: Option<HashMap<String, String>>,
pub proxy: Option<SocketAddr>,
#[serde(default)]
pub connect_timeout: u64,
#[serde(default)]
pub read_timeout: u64,
#[serde(default)]
pub write_timeout: u64,
}
impl WebSocketOptions {
pub fn try_from(x: AnyLuaValue) -> Result<WebSocketOptions> {
let x = LuaJsonValue::from(x);
let x = serde_json::from_value(x.into())?;
Ok(x)
}
}
pub enum Event {
Text(String),
Binary(Vec<u8>),
Close,
Timeout,
}
pub struct WebSocket {
sock: protocol::WebSocket<Stream>,
}
impl WebSocket {
pub fn negotiate(
stream: Stream,
url: Url,
headers: Option<&HashMap<String, String>>,
) -> Result<WebSocket> {
let mut req = Request::get(url.to_string()); // TODO: don't re-parse here
if let Some(headers) = headers {
for (k, v) in headers {
req = req.header(k, v);
}
}
let req = req.body(()).unwrap();
let (sock, _resp) = tungstenite::client::client(req, stream)?;
Ok(WebSocket { sock })
}
pub fn connect<R: DnsResolver>(
resolver: &R,
url: Url,
options: &WebSocketOptions,
) -> Result<WebSocket> {
let tls = match url.scheme() {
"ws" => false,
"wss" => true,
_ => bail!("Invalid websocket protocol"),
};
let host = url
.host_str()
.ok_or_else(|| format_err!("Missing host in url"))?;
let port = match (url.port(), tls) {
(Some(port), _) => port,
(None, true) => 443,
(None, false) => 80,
};
let stream = Stream::connect_stream(
resolver,
host,
port,
&SocketOptions {
tls,
sni_value: None,
disable_tls_verify: false,
proxy: options.proxy,
connect_timeout: options.connect_timeout,
read_timeout: options.read_timeout,
write_timeout: options.write_timeout,
},
)?;
Self::negotiate(stream, url, options.headers.as_ref())
}
pub fn options(&self, options: &WebSocketOptions) -> Result<()> {
let o = SocketOptions {
read_timeout: options.read_timeout,
write_timeout: options.write_timeout,
..Default::default()
};
o.apply(self.sock.get_ref())
}
fn read_msg(&mut self) -> Result<Event> {
loop {
let msg = match self.sock.read_message() {
Ok(Message::Text(body)) => Event::Text(body),
Ok(Message::Binary(body)) => Event::Binary(body),
Ok(Message::Ping(ping)) => {
self.sock.write_message(Message::Pong(ping))?;
continue;
}
Ok(Message::Pong(_)) => continue, // this should never happen
Ok(Message::Close(_)) => Event::Close,
Err(tungstenite::Error::ConnectionClosed) => Event::Close,
Err(tungstenite::Error::AlreadyClosed) => Event::Close,
Err(tungstenite::Error::Io(err)) if err.kind() == io::ErrorKind::WouldBlock => {
Event::Timeout
}
Err(err) => return Err(err.into()),
};
return Ok(msg);
}
}
pub fn read_text(&mut self) -> Result<Option<String>> {
match self.read_msg()? {
Event::Text(text) => Ok(Some(text)),
Event::Binary(_) => bail!("Unexpected message type: binary"),
Event::Close => bail!("Connection closed"),
Event::Timeout => Ok(None),
}
}
pub fn read_binary(&mut self) -> Result<Option<Vec<u8>>> {
match self.read_msg()? {
Event::Text(_) => bail!("Unexpected message type: text"),
Event::Binary(body) => Ok(Some(body)),
Event::Close => bail!("Connection closed"),
Event::Timeout => Ok(None),
}
}
fn write_msg(&mut self, msg: Message) -> Result<()> {
self.sock.write_message(msg)?;
self.sock.write_pending()?;
Ok(())
}
pub fn write_text(&mut self, text: String) -> Result<()> {
self.write_msg(Message::Text(text))
}
pub fn write_binary(&mut self, binary: Vec<u8>) -> Result<()> {
self.write_msg(Message::Binary(binary))
}
}