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
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
//! rust websocket toolkit

#![warn(missing_docs)]

use std::collections::HashMap;
use std::fmt::Debug;

use bytes::{Bytes, BytesMut};
use frame::{BorrowedFrame, OpCode, ReadFrame};

/// websocket error definitions
pub mod errors;
/// websocket transport unit
pub mod frame;
/// build connection & read/write frame utils
pub mod protocol;

#[cfg(any(feature = "async_proxy"))]
/// connection proxy support
pub mod proxy;

/// stream definition
pub mod stream;

/// frame codec impl
pub mod codec;

/// websocket connection state
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum ConnectionState {
    /// init state
    Created,
    /// tcp & tls connection creating state
    HandShaking,
    /// websocket connection has been successfully established
    Running,
    /// client or peer has send "close frame"
    Closing,
    /// client or peer have send "close" response frame
    Closed,
}

/// helper builder to construct websocket client
#[allow(dead_code)]
pub struct ClientBuilder {
    uri: String,
    #[cfg(any(feature = "async_proxy"))]
    proxy_uri: Option<String>,
    protocols: Vec<String>,
    extensions: Vec<String>,
    #[cfg(any(feature = "async_tls_rustls", feature = "tls_rustls"))]
    certs: std::collections::HashSet<std::path::PathBuf>,
    version: u8,
    headers: HashMap<String, String>,
}

impl ClientBuilder {
    /// create builder with websocket url
    pub fn new<S: ToString>(uri: S) -> Self {
        Self {
            uri: uri.to_string(),
            #[cfg(any(feature = "async_proxy"))]
            proxy_uri: None,
            protocols: vec![],
            extensions: vec![],
            headers: HashMap::new(),
            #[cfg(any(feature = "async_tls_rustls", feature = "tls_rustls"))]
            certs: std::collections::HashSet::new(),
            version: 13,
        }
    }

    /// set websocket proxy
    #[cfg(any(feature = "async_proxy"))]
    pub fn proxy<S: ToString>(self, uri: S) -> Self {
        Self {
            proxy_uri: Some(uri.to_string()),
            ..self
        }
    }

    /// add protocols
    pub fn protocol(mut self, protocol: String) -> Self {
        self.protocols.push(protocol);
        self
    }

    /// set extension in handshake http header
    ///
    /// **NOTE** it will clear protocols set by `protocol` method
    pub fn protocols(self, protocols: Vec<String>) -> Self {
        Self { protocols, ..self }
    }

    /// add protocols
    pub fn extension(mut self, extension: String) -> Self {
        self.extensions.push(extension);
        self
    }

    /// set extension in handshake http header
    ///
    /// **NOTE** it will clear protocols set by `protocol` method
    pub fn extensions(self, extensions: Vec<String>) -> Self {
        Self { extensions, ..self }
    }

    #[cfg(any(feature = "async_tls_rustls", feature = "tls_rustls"))]
    /// set ssl cert in wss connection
    pub fn cert(mut self, cert: std::path::PathBuf) -> Self {
        self.certs.insert(cert);
        self
    }

    #[cfg(any(feature = "async_tls_rustls", feature = "tls_rustls"))]
    // set ssl certs in wss connection
    ///
    /// **NOTE** it will clear certs set by `cert` method
    pub fn certs(self, certs: std::collections::HashSet<std::path::PathBuf>) -> Self {
        Self { certs, ..self }
    }

    /// set websocket version
    pub fn version(self, version: u8) -> Self {
        Self { version, ..self }
    }

    /// add initial request header
    pub fn header<K: ToString, V: ToString>(mut self, name: K, value: V) -> Self {
        self.headers.insert(name.to_string(), value.to_string());
        self
    }

    /// set initial request headers
    ///
    /// **NOTE** it will clear header set by previous `header` method
    pub fn headers(self, headers: HashMap<String, String>) -> Self {
        Self { headers, ..self }
    }
}

#[cfg(feature = "blocking")]
mod blocking {
    use std::{
        io::{Read, Write},
        net::TcpStream,
    };

    use crate::{
        errors::WsError,
        protocol::{handle_handshake, req_handshake, Mode},
        stream::WsStream,
        ClientBuilder, ServerBuilder,
    };

    impl ClientBuilder {
        fn _connect(&self) -> Result<(String, http::Response<()>, WsStream<TcpStream>), WsError> {
            let Self {
                uri,
                protocols,
                extensions,
                #[cfg(feature = "tls_rustls")]
                certs,
                version,
                headers,
                ..
            } = self;
            let uri = uri
                .parse::<http::Uri>()
                .map_err(|e| WsError::InvalidUri(format!("{} {}", uri, e)))?;
            let mode = if let Some(schema) = uri.scheme_str() {
                match schema.to_ascii_lowercase().as_str() {
                    "ws" => Ok(Mode::WS),
                    "wss" => Ok(Mode::WSS),
                    _ => Err(WsError::InvalidUri(format!("invalid schema {}", schema))),
                }
            } else {
                Err(WsError::InvalidUri("missing ws or wss schema".to_string()))
            }?;
            #[cfg(feature = "tls_rustls")]
            if mode == Mode::WS && !certs.is_empty() {
                tracing::warn!("setting tls cert has no effect on insecure ws")
            }
            let host = uri
                .host()
                .ok_or_else(|| WsError::InvalidUri(format!("can not find host {}", self.uri)))?;
            let port = match uri.port_u16() {
                Some(port) => port,
                None => mode.default_port(),
            };

            let stream = TcpStream::connect((host, port)).map_err(|e| {
                WsError::ConnectionFailed(format!("failed to create tcp connection {}", e))
            })?;

            tracing::debug!("tcp connection established");

            let mut stream = match mode {
                Mode::WS => WsStream::Plain(stream),
                Mode::WSS => {
                    #[cfg(feature = "tls_rustls")]
                    {
                        use crate::protocol::wrap_tls;
                        let tls_stream = wrap_tls(stream, host, &self.certs)?;
                        WsStream::Tls(tls_stream)
                    }

                    #[cfg(not(feature = "tls_rustls"))]
                    {
                        panic!("require `rustls`")
                    }
                }
            };
            let (key, resp) = req_handshake(
                &mut stream,
                &mode,
                &uri,
                protocols.to_vec().join(" ,"),
                extensions.to_vec().join(" ,"),
                *version,
                headers.clone(),
            )?;
            Ok((key, resp, stream))
        }

        /// perform protocol handshake & check server response
        pub fn connect<C, F>(&self, check_fn: F) -> Result<C, WsError>
        where
            F: Fn(String, http::Response<()>, WsStream<TcpStream>) -> Result<C, WsError>,
        {
            let (key, resp, stream) = self._connect()?;
            check_fn(key, resp, stream)
        }
    }

    impl ServerBuilder {
        /// wait for protocol handshake from client
        /// checking handshake & construct server
        pub fn accept<F1, F2, T, C, S>(
            stream: S,
            handshake_handler: F1,
            codec_factory: F2,
        ) -> Result<C, WsError>
        where
            S: Read + Write,
            F1: Fn(http::Request<()>) -> Result<(http::Request<()>, http::Response<T>), WsError>,
            F2: Fn(http::Request<()>, WsStream<S>) -> Result<C, WsError>,
            T: ToString + std::fmt::Debug,
        {
            let mut stream = WsStream::Plain(stream);
            let req = handle_handshake(&mut stream)?;
            let (req, resp) = handshake_handler(req)?;
            let mut resp_lines = vec![format!("{:?} {}", resp.version(), resp.status())];
            resp.headers().iter().for_each(|(k, v)| {
                resp_lines.push(format!("{}: {}", k, v.to_str().unwrap_or_default()))
            });
            resp_lines.push("\r\n".to_string());
            stream.write_all(resp_lines.join("\r\n").as_bytes())?;
            tracing::debug!("{:?}", &resp);
            if resp.status() != http::StatusCode::SWITCHING_PROTOCOLS {
                return Err(WsError::HandShakeFailed(resp.body().to_string()));
            }
            codec_factory(req, stream)
        }
    }
}

#[cfg(feature = "async")]
mod non_blocking {
    use std::fmt::Debug;

    use bytes::BytesMut;
    use tokio::{
        io::{AsyncRead, AsyncWrite, AsyncWriteExt},
        net::TcpStream,
    };

    use crate::{
        errors::WsError,
        protocol::{async_handle_handshake, async_req_handshake, Mode},
        stream::WsAsyncStream,
        ServerBuilder,
    };

    use super::ClientBuilder;

    impl ClientBuilder {
        async fn _async_connect(
            &self,
        ) -> Result<
            (
                String,
                http::Response<()>,
                BytesMut,
                WsAsyncStream<TcpStream>,
            ),
            WsError,
        > {
            let Self {
                uri,
                #[cfg(feature = "async_proxy")]
                proxy_uri,
                protocols,
                extensions,
                #[cfg(feature = "async_tls_rustls")]
                certs,
                version,
                headers,
            } = self;
            let uri = uri
                .parse::<http::Uri>()
                .map_err(|e| WsError::InvalidUri(format!("{} {}", uri, e)))?;
            let mode = if let Some(schema) = uri.scheme_str() {
                match schema.to_ascii_lowercase().as_str() {
                    "ws" => Ok(Mode::WS),
                    "wss" => Ok(Mode::WSS),
                    _ => Err(WsError::InvalidUri(format!("invalid schema {}", schema))),
                }
            } else {
                Err(WsError::InvalidUri("missing ws or wss schema".to_string()))
            }?;
            #[cfg(feature = "async_tls_rustls")]
            if mode == Mode::WS && !certs.is_empty() {
                tracing::warn!("setting tls cert has no effect on insecure ws")
            }
            let host = uri
                .host()
                .ok_or_else(|| WsError::InvalidUri(format!("can not find host {}", self.uri)))?;
            let port = match uri.port_u16() {
                Some(port) => port,
                None => mode.default_port(),
            };

            let stream;
            #[cfg(feature = "async_proxy")]
            {
                let ws_proxy: Option<super::proxy::Proxy> = match proxy_uri {
                    Some(uri) => Some(uri.parse()?),
                    None => None,
                };
                stream = match &ws_proxy {
                    Some(proxy_conf) => proxy_conf.connect((host, port)).await?,
                    None => TcpStream::connect((host, port)).await.map_err(|e| {
                        WsError::ConnectionFailed(format!("failed to create tcp connection {}", e))
                    })?,
                };
            }

            #[cfg(not(feature = "async_proxy"))]
            {
                stream = TcpStream::connect((host, port)).await.map_err(|e| {
                    WsError::ConnectionFailed(format!(
                        "failed to create tcp connection {}",
                        e.to_string()
                    ))
                })?;
            }

            tracing::debug!("tcp connection established");

            let mut stream = match mode {
                Mode::WS => WsAsyncStream::Plain(stream),
                Mode::WSS => {
                    #[cfg(feature = "async_tls_rustls")]
                    {
                        use crate::protocol::async_wrap_tls;
                        let tls_stream = async_wrap_tls(stream, host, &self.certs).await?;
                        WsAsyncStream::Tls(tls_stream)
                    }

                    #[cfg(not(feature = "async_tls_rustls"))]
                    {
                        panic!("require `rustls`")
                    }
                }
            };
            let (key, resp, remain) = async_req_handshake(
                &mut stream,
                &mode,
                &uri,
                protocols.to_vec().join(" ,"),
                extensions.to_vec().join(" ,"),
                *version,
                headers.clone(),
            )
            .await?;
            Ok((key, resp, remain, stream))
        }

        /// async version of connect
        ///
        /// perform protocol handshake & check server response
        pub async fn async_connect<C, F>(&self, check_fn: F) -> Result<C, WsError>
        where
            F: Fn(
                String,
                http::Response<()>,
                BytesMut,
                WsAsyncStream<TcpStream>,
            ) -> Result<C, WsError>,
        {
            let (key, resp, remain, stream) = self._async_connect().await?;
            check_fn(key, resp, remain, stream)
        }
    }

    impl ServerBuilder {
        /// async version
        ///
        /// wait for protocol handshake from client
        /// checking handshake & construct server
        pub async fn async_accept<F1, F2, T, C, S>(
            stream: S,
            handshake_handler: F1,
            codec_factory: F2,
        ) -> Result<C, WsError>
        where
            S: AsyncRead + AsyncWrite + Unpin,
            F1: Fn(http::Request<()>) -> Result<(http::Request<()>, http::Response<T>), WsError>,
            F2: Fn(http::Request<()>, BytesMut, WsAsyncStream<S>) -> Result<C, WsError>,
            T: ToString + Debug,
        {
            let mut stream = WsAsyncStream::Plain(stream);
            let (req, remain) = async_handle_handshake(&mut stream).await?;
            let (req, resp) = handshake_handler(req)?;
            let mut resp_lines = vec![format!("{:?} {}", resp.version(), resp.status())];
            resp.headers().iter().for_each(|(k, v)| {
                resp_lines.push(format!("{}: {}", k, v.to_str().unwrap_or_default()))
            });
            resp_lines.push("\r\n".to_string());
            stream.write_all(resp_lines.join("\r\n").as_bytes()).await?;
            tracing::debug!("{:?}", &resp);
            if resp.status() != http::StatusCode::SWITCHING_PROTOCOLS {
                return Err(WsError::HandShakeFailed(resp.body().to_string()));
            }
            codec_factory(req, remain, stream)
        }
    }
}

/// helper struct to config & construct websocket server
pub struct ServerBuilder {}

/// a trait that tells ws-tool corresponding opcode of custom type
pub trait DefaultCode {
    /// get payload opcode
    fn code(&self) -> OpCode;
}

impl DefaultCode for String {
    fn code(&self) -> OpCode {
        OpCode::Text
    }
}

impl DefaultCode for &[u8] {
    fn code(&self) -> OpCode {
        OpCode::Binary
    }
}
impl DefaultCode for &mut [u8] {
    fn code(&self) -> OpCode {
        OpCode::Binary
    }
}

impl DefaultCode for BytesMut {
    fn code(&self) -> OpCode {
        OpCode::Binary
    }
}

impl DefaultCode for Bytes {
    fn code(&self) -> OpCode {
        OpCode::Binary
    }
}

impl DefaultCode for ReadFrame {
    fn code(&self) -> OpCode {
        self.header().opcode()
    }
}

impl<'a> DefaultCode for BorrowedFrame<'a> {
    fn code(&self) -> OpCode {
        self.header().opcode()
    }
}

/// generic message receive/send from websocket stream
pub struct Message<T: AsRef<[u8]> + DefaultCode> {
    /// opcode of message
    ///
    /// see all codes in [overview](https://datatracker.ietf.org/doc/html/rfc6455#section-5.2) of opcode
    pub code: OpCode,
    /// payload of message
    pub data: T,

    /// available in close frame only
    ///
    /// see [status code](https://datatracker.ietf.org/doc/html/rfc6455#section-7.4)
    pub close_code: Option<u16>,
}

impl<T: AsRef<[u8]> + DefaultCode> Message<T> {
    /// consume message and return payload
    pub fn into(self) -> T {
        self.data
    }
}

impl<T: AsRef<[u8]> + DefaultCode> From<(OpCode, T)> for Message<T> {
    fn from(data: (OpCode, T)) -> Self {
        let close_code = if data.0 == OpCode::Close {
            Some(1000)
        } else {
            None
        };
        Self {
            data: data.1,
            code: data.0,
            close_code,
        }
    }
}

impl<T: AsRef<[u8]> + DefaultCode> From<(u16, T)> for Message<T> {
    fn from(data: (u16, T)) -> Self {
        Self {
            code: OpCode::Close,
            close_code: Some(data.0),
            data: data.1,
        }
    }
}

impl<T: AsRef<[u8]> + DefaultCode> From<T> for Message<T> {
    fn from(data: T) -> Self {
        Self {
            code: data.code(),
            data,
            close_code: None,
        }
    }
}