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
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362

use std::str::Utf8Error;

use log_to_stdout::error;

#[doc(hidden)]
pub use hyper::upgrade;

use tokio_tungstenite::WebSocketStream;
use tokio_tungstenite::tungstenite;
use tungstenite::protocol::Role;

// rexport
use tungstenite::protocol::Message as ProtMessage;
pub use tungstenite::{
	error::Error,
	protocol::CloseFrame,
	protocol::frame::coding::CloseCode
};

use futures_util::stream::StreamExt;
use futures_util::sink::SinkExt;

use sha1::Digest;

// See: https://github.com/hyperium/hyper/blob/master/examples/upgrades.rs

// we first need to implement raw routes

/*
// data might be needed to be cloned
ws_route!(MyRoute, "path", |ws, data| {
	// this is spawned in a new task
	// anything happens here
});
*/

// Basic Route
/// Creates a WebSocket route
///
/// Because this spawns a new task it will clone every used data
#[macro_export]
macro_rules! ws_route {
	($name:ident, $($tt:tt)* ) => (
		$crate::ws_route!($name<Data>, $($tt)*);
	);
	($name:ident<$data_ty:ty>, $path:expr, |$ws:ident| $block:block ) => (
		$crate::ws_route!($name<$data_ty>, $path, |$ws,| -> () $block);
	);
	($name:ident<$data_ty:ty>, $path:expr, |$ws:ident| -> $ret_type:ty $block:block ) => (
		$crate::ws_route!($name<$data_ty>, $path, |$ws,| -> $ret_type $block);
	);
	($name:ident<$data_ty:ty>, $path:expr, |$ws:ident| -> $ret_type:ty $block:block, |$ret:ident| $ret_block:block ) => (
		$crate::ws_route!($name<$data_ty>, $path, |$ws,| -> $ret_type $block, |$ret| $ret_block);
	);
	($name:ident<$data_ty:ty>, $path:expr, |$ws:ident, $( $data:ident ),*| -> $ret_type:ty $block:block ) => (
		$crate::ws_route!($name<$data_ty>, $path, |$ws, $($data),*| -> $ret_type $block, |ret| { ret });
	);
	($name:ident<$data_ty:ty>, $path:expr, |$ws:ident, $( $data:ident ),*| -> $ret_type:ty $block:block, |$ret:ident| $ret_block:block ) => (

		pub struct $name;

		impl $crate::routes::RawRoute<$data_ty> for $name {

			fn check(&self, req: &$crate::request::HyperRequest) -> bool {
				req.method().as_str() == "GET" &&
				$crate::routes::check_static( req.uri().path(), $path )
			}

			fn call<'a>(
				&'a self,
				req: &'a mut $crate::request::RequestBuilder<'_>,
				raw_data: &'a $data_ty
			) -> $crate::util::PinnedFuture<'a, Option<$crate::Result<$crate::http::Response>>> {

				use $crate::into::IntoRouteResult;

				$crate::util::PinnedFuture::new( async move {

					// allowed to unwrap (will not panic)
					let hyper_req = req.hyper_mut().unwrap();

					// if headers not match for websocket
					// return bad request
					let header_upgrade = hyper_req.headers()
						.get("upgrade")
						.and_then(|v| v.to_str().ok());
					let header_version = hyper_req.headers()
						.get("sec-websocket-version")
						.and_then(|v| v.to_str().ok());
					let websocket_key = hyper_req.headers()
						.get("sec-websocket-key")
						.map(|v| v.as_bytes());

					if !matches!(
						(header_upgrade, header_version, websocket_key),
						(Some("websocket"), Some("13"), Some(k))
					) {
						return Some(Err($crate::error::ClientErrorKind::BadRequest.into()))
					}


					// calculate websocket key stuff
					// unwrap does not fail because we check above
					let websocket_key = websocket_key.unwrap();
					let ws_accept = $crate::ws::ws_accept(websocket_key);

					$( let mut $data = raw_data.$data().clone(); )*

					let on_upgrade = $crate::ws::upgrade::on(hyper_req);


					// we need to spawn a future because
					// upgrade on can only be fufilled after
					// we send SWITCHING_PROTOCOLS
					tokio::task::spawn(async move {
						match on_upgrade.await {
							Ok(upgraded) => {
								let mut $ws = $crate::ws::WebSocket::new(upgraded).await;
								let $ret: $ret_type = async move { $block }.await;
								let _: () = { $ret_block };
							},
							Err(e) => $crate::ws::upgrade_error(e)
						}
					});


					Some(Ok(
						$crate::http::Response::builder()
							.status_code($crate::http::header::StatusCode::SwitchingProtocols)
							.header("connection", "upgrade")
							.header("upgrade", "websocket")
							.header("sec-websocket-accept", ws_accept)
							.build()
						//.into()
					))
				} )
			}

		}

	)
}


#[doc(hidden)]
pub fn upgrade_error(e: hyper::Error) {
	error!("upgrade error {:?}", e);
}

// does the key need to be a specific length?
#[doc(hidden)]
pub fn ws_accept(key: &[u8]) -> String {
	let mut sha1 = sha1::Sha1::new();
	sha1.update(key);
	sha1.update(b"258EAFA5-E914-47DA-95CA-C5AB0DC85B11");
	// cannot fail because 
	base64::encode(sha1.finalize())
}

#[cfg(feature = "json")]
macro_rules! try2 {
	($e:expr) => (match $e {
		Some(v) => v,
		None => return Ok(None)
	})
}

#[derive(Debug, Clone, PartialEq, Eq, Hash)]
pub enum Message {
	Text(String),
	Binary(Vec<u8>)
}

impl Message {
	pub fn into_data(self) -> Vec<u8> {
		match self {
			Self::Text(t) => t.into(),
			Self::Binary(b) => b
		}
	}

	pub fn to_text(&self) -> Result<&str, Utf8Error> {
		match self {
			Self::Text(t) => Ok(&t),
			Self::Binary(b) => std::str::from_utf8(b)
		}
	}
}

impl From<String> for Message {
	fn from(s: String) -> Self {
		Self::Text(s)
	}
}

impl From<&str> for Message {
	fn from(s: &str) -> Self {
		Self::Text(s.into())
	}
}

impl From<Vec<u8>> for Message {
	fn from(v: Vec<u8>) -> Self {
		Self::Binary(v)
	}
}

impl From<&[u8]> for Message {
	fn from(v: &[u8]) -> Self {
		Self::Binary(v.into())
	}
}

impl From<Message> for ProtMessage {
	fn from(m: Message) -> Self {
		match m {
			Message::Text(t) => Self::Text(t),
			Message::Binary(b) => Self::Binary(b)
		}
	}
}


#[derive(Debug)]
pub struct WebSocket {
	inner: WebSocketStream<upgrade::Upgraded>
}

impl WebSocket {

	pub async fn new(upgraded: upgrade::Upgraded) -> Self {
		Self {
			inner: WebSocketStream::from_raw_socket(
				upgraded,
				Role::Server,
				None
			).await
		}
	}

	// used for tests
	#[doc(hidden)]
	pub fn from_raw(
		inner: WebSocketStream<upgrade::Upgraded>
	) -> Self {
		Self { inner }
	}

	/// Handles Ping and Pong messages
	/// 
	/// never returns Error::ConnectionClose | Error::AlreadyClosed
	pub async fn receive(&mut self) -> Result<Option<Message>, Error> {
		// loop used to handle Message::Pong | Message::Ping
		loop {
			let res = self.inner.next().await.transpose();
			return match res {
				Ok(None) => Ok(None),
				Ok(Some(ProtMessage::Text(t))) => Ok(Some(Message::Text(t))),
				Ok(Some(ProtMessage::Binary(b))) => {
					Ok(Some(Message::Binary(b)))
				},
				Ok(Some(ProtMessage::Ping(d))) => {
					// respond with a pong
					self.inner.send(ProtMessage::Pong(d)).await?;
					// then listen for a new message
					continue
				},
				Ok(Some(ProtMessage::Pong(_))) => continue,
				Ok(Some(ProtMessage::Close(_))) => Ok(None),
				Ok(Some(ProtMessage::Frame(f))) => {
					eprintln!("received frame {:?} ?? what todo?", f);
					continue
				},
				Err(Error::ConnectionClosed) |
				Err(Error::AlreadyClosed) => Ok(None),
				Err(e) => Err(e)
			};
		}
	}

	pub async fn send<M>(&mut self, msg: M) -> Result<(), Error>
	where M: Into<Message> {
		self.inner.send(msg.into().into()).await
	}

	pub async fn close(&mut self, code: CloseCode, reason: String) {
		let _ = self.inner.send(ProtMessage::Close(Some(CloseFrame {
			code, reason: reason.into()
		}))).await;
		let _ = self.inner.close(None).await;
		// close is close
		// don't mind if you could send close or not
	}

	pub async fn ping(&mut self) -> Result<(), Error> {
		self.inner.send(ProtMessage::Ping(vec![])).await
	}

	/// calls receive and then deserialize
	#[cfg(feature = "json")]
	pub async fn deserialize<D>(&mut self) -> Result<Option<D>, JsonError>
	where D: serde::de::DeserializeOwned {
		let msg = try2!(self.receive().await?).into_data();
		serde_json::from_slice(&msg)
			.map(|d| Some(d))
			.map_err(|e| e.into())
	}

	/// calls serialize then send
	#[cfg(feature = "json")]
	pub async fn serialize<S: ?Sized>(&mut self, value: &S) -> Result<(), JsonError>
	where S: serde::Serialize {
		let v = serde_json::to_string(value)?;
		self.send(v).await
			.map_err(|e| e.into())
	}

}

#[cfg(feature = "json")]
mod json_error {

	use super::Error;
	use std::fmt;

	#[derive(Debug)]
	pub enum JsonError {
		ConnectionError(Error),
		SerdeError(serde_json::Error)
	}

	impl From<Error> for JsonError {
		fn from(e: Error) -> Self {
			Self::ConnectionError(e)
		}
	}

	impl From<serde_json::Error> for JsonError {
		fn from(e: serde_json::Error) -> Self {
			Self::SerdeError(e)
		}
	}

	impl fmt::Display for JsonError {
		fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
			fmt::Debug::fmt(self, f)
		}
	}

	impl std::error::Error for JsonError {
		fn source(&self) -> Option<&(dyn std::error::Error + 'static)> {
			match self {
				Self::ConnectionError(e) => Some(e),
				Self::SerdeError(e) => Some(e)
			}
		}
	}
}

#[cfg(feature = "json")]
pub use json_error::JsonError;