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
#![allow(clippy::unusual_byte_groupings)]
use crate::{errors::err, *};

#[cfg(feature = "client")]
/// client specific implementation
pub mod client;

#[cfg(feature = "server")]
/// server specific implementation
pub mod server;

type EventAction = std::result::Result<(), Box<dyn std::error::Error + Send + Sync>>;

/// WebSocket implementation for both client and server
pub struct WebSocket<const SIDE: bool, Stream> {
    /// it is a low-level abstraction that represents the underlying byte stream over which WebSocket messages are exchanged.
    pub stream: Stream,

    /// Listen for incoming websocket [Event].
    ///
    /// ### Example
    ///
    /// ```no_run
    /// use web_socket::{client::WS, Event};
    /// # async {
    ///
    /// let mut ws = WS::connect("localhost:80", "/").await?;
    /// // Fire when received ping/pong frame.
    /// ws.on_event = Box::new(|ev| {
    ///     println!("{ev:?}");
    ///     Ok(())
    /// });
    ///
    /// # std::io::Result::<_>::Ok(()) };
    /// ```
    pub on_event: Box<dyn FnMut(Event) -> EventAction + Send + Sync>,

    /// used in `cls_if_err`
    is_closed: bool,

    fin: bool,
    len: usize,
}

impl<const SIDE: bool, W: Unpin + AsyncWrite> WebSocket<SIDE, W> {
    /// Send message to a endpoint by writing it to a WebSocket stream.
    ///
    /// ### Example
    ///
    /// ```no_run
    /// use web_socket::{client::WS, CloseCode, Event};
    /// # async {
    ///
    /// let mut ws = WS::connect("localhost:80", "/").await?;
    /// ws.send("Text Message").await?;
    /// ws.send(b"Binary Data").await?;
    ///
    /// // You can also send control frame.
    /// ws.send(Event::Ping(b"Hello!")).await?;
    /// ws.send(Event::Pong(b"Hello!")).await?;
    ///
    /// # std::io::Result::<_>::Ok(()) };
    /// ```
    #[inline]
    pub async fn send(&mut self, msg: impl Message) -> Result<()> {
        let mut bytes = vec![];
        msg.encode::<SIDE>(&mut bytes);
        self.stream.write_all(&bytes).await
    }

    /// Flushes this output stream, ensuring that all intermediately buffered contents reach their destination.
    #[inline]
    pub async fn flash(&mut self) -> Result<()> {
        self.stream.flush().await
    }

    /// - The Close frame MAY contain a body that indicates a reason for closing.
    ///
    /// ### Example
    ///
    /// ```no_run
    /// use web_socket::{client::WS, CloseCode};
    /// # async {
    ///
    /// let ws = WS::connect("localhost:80", "/").await?;
    /// ws.close((CloseCode::Normal, "Closed successfully")).await?;
    ///
    /// # std::io::Result::<_>::Ok(()) };
    /// ```
    pub async fn close<T>(mut self, reason: T) -> Result<()>
    where
        T: CloseFrame,
        T::Frame: AsRef<[u8]>,
    {
        self.stream
            .write_all(reason.encode::<SIDE>().as_ref())
            .await?;
        self.stream.flush().await
    }
}

impl<const SIDE: bool, Stream> From<Stream> for WebSocket<SIDE, Stream> {
    #[inline]
    fn from(stream: Stream) -> Self {
        Self {
            stream,
            on_event: Box::new(|_| Ok(())),

            is_closed: false,

            fin: true,
            len: 0,
        }
    }
}

impl<const SIDE: bool, IO: Unpin + AsyncRead + AsyncWrite> WebSocket<SIDE, IO> {
    /// ### WebSocket Frame Header
    ///
    /// ```txt
    ///  0                   1                   2                   3
    ///  0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1
    /// +-+-+-+-+-------+-+-------------+-------------------------------+
    /// |F|R|R|R| opcode|M| Payload len |    Extended payload length    |
    /// |I|S|S|S|  (4)  |A|     (7)     |             (16/64)           |
    /// |N|V|V|V|       |S|             |   (if payload len==126/127)   |
    /// | |1|2|3|       |K|             |                               |
    /// +-+-+-+-+-------+-+-------------+ - - - - - - - - - - - - - - - +
    /// |     Extended payload length continued, if payload len == 127  |
    /// + - - - - - - - - - - - - - - - +-------------------------------+
    /// |                               |Masking-key, if MASK set to 1  |
    /// +-------------------------------+-------------------------------+
    /// | Masking-key (continued)       |          Payload Data         |
    /// +-------------------------------- - - - - - - - - - - - - - - - +
    /// :                     Payload Data continued ...                :
    /// + - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - +
    /// |                     Payload Data continued ...                |
    /// +---------------------------------------------------------------+
    /// ```
    async fn header(&mut self) -> Result<(bool, u8, usize)> {
        loop {
            let [b1, b2] = read_buf(&mut self.stream).await?;

            let fin = b1 & 0b_1000_0000 != 0;
            let rsv = b1 & 0b_111_0000;
            let opcode = b1 & 0b_1111;
            let len = (b2 & 0b_111_1111) as usize;

            // Defines whether the "Payload data" is masked.  If set to 1, a
            // masking key is present in masking-key, and this is used to unmask
            // the "Payload data" as per [Section 5.3](https://datatracker.ietf.org/doc/html/rfc6455#section-5.3).  All frames sent from
            // client to server have this bit set to 1.
            let is_masked = b2 & 0b_1000_0000 != 0;

            if rsv != 0 {
                // MUST be `0` unless an extension is negotiated that defines meanings
                // for non-zero values.  If a nonzero value is received and none of
                // the negotiated extensions defines the meaning of such a nonzero
                // value, the receiving endpoint MUST _Fail the WebSocket Connection_.
                err!(CloseEvent::Error("reserve bit MUST be `0`"));
            }

            // A client MUST mask all frames that it sends to the server. (Note
            // that masking is done whether or not the WebSocket Protocol is running
            // over TLS.)  The server MUST close the connection upon receiving a
            // frame that is not masked.
            //
            // A server MUST NOT mask any frames that it sends to the client.
            if SERVER == SIDE {
                if !is_masked {
                    err!(CloseEvent::Error("expected masked frame"));
                }
            } else if is_masked {
                err!(CloseEvent::Error("expected unmasked frame"));
            }

            // 3-7 are reserved for further non-control frames.
            if opcode >= 8 {
                if !fin {
                    err!(CloseEvent::Error("control frame MUST NOT be fragmented"));
                }
                if len > 125 {
                    err!(CloseEvent::Error(
                        "control frame MUST have a payload length of 125 bytes or less"
                    ));
                }

                let mut msg = vec![0; len];
                if SERVER == SIDE {
                    let mut mask = Mask::from(read_buf(&mut self.stream).await?);
                    self.stream.read_exact(&mut msg).await?;
                    msg.iter_mut()
                        .zip(&mut mask)
                        .for_each(|(byte, key)| *byte ^= key);
                } else {
                    self.stream.read_exact(&mut msg).await?;
                }

                match opcode {
                    // Close
                    8 => {
                        // - If there is a body, the first two bytes of the body MUST be a 2-byte unsigned integer (in network byte order: Big Endian)
                        //   representing a status code with value /code/ defined in [Section 7.4](https://datatracker.ietf.org/doc/html/rfc6455#section-7.4). Following the 2-byte integer,
                        //
                        // - Close frames sent from client to server must be masked.
                        // - The application MUST NOT send any more data frames after sending a `Close` frame.
                        //
                        // - If an endpoint receives a Close frame and did not previously send a
                        //   Close frame, the endpoint MUST send a Close frame in response.  (When
                        //   sending a Close frame in response, the endpoint typically echos the
                        //   status code it received.)  It SHOULD do so as soon as practical.  An
                        //   endpoint MAY delay sending a Close frame until its current message is
                        //   sent
                        //
                        // - After both sending and receiving a Close message, an endpoint
                        //   considers the WebSocket connection closed and MUST close the
                        //   underlying TCP connection.
                        let code = msg
                            .get(..2)
                            .map(|bytes| u16::from_be_bytes([bytes[0], bytes[1]]))
                            .unwrap_or(1000);

                        let mut reason = String::new().into_boxed_str();

                        if let 1000..=1003 | 1007..=1011 | 1015 | 3000..=3999 | 4000..=4999 = code {
                            match msg.get(2..).map(|data| String::from_utf8(data.to_vec())) {
                                Some(Ok(msg)) => reason = msg.into_boxed_str(),
                                Some(Err(_)) => err!(CloseEvent::Error("invalid utf-8 payload")),
                                _ => {}
                            }
                            let mut writer = vec![];
                            message::encode::<SIDE>(&mut writer, true, 8, &msg);
                            let _ = self.stream.write_all(&writer).await;
                        }
                        err!(CloseEvent::Close { code, reason });
                    }
                    // Ping
                    9 => {
                        // A Ping frame MAY include "Application data".
                        // Unless it already received a Close frame.  It SHOULD respond with Pong frame as soon as is practical.
                        //
                        // A Ping frame may serve either as a keepalive or as a means to verify that the remote endpoint is still responsive.
                        if let Err(reason) = (self.on_event)(Event::Ping(&msg)) {
                            let _ = self
                                .stream
                                .write_all(&CloseFrame::encode::<SIDE>(reason.to_string().as_str()))
                                .await;

                            err!(reason);
                        };
                        self.send(Event::Pong(&msg)).await?;
                    }
                    // Pong
                    10 => {
                        // A Pong frame sent in response to a Ping frame must have identical
                        // "Application data" as found in the message body of the Ping frame being replied to.
                        //
                        // If an endpoint receives a Ping frame and has not yet sent Pong frame(s) in response to previous Ping frame(s), the endpoint MAY
                        // elect to send a Pong frame for only the most recently processed Ping frame.
                        //
                        //  A Pong frame MAY be sent unsolicited.  This serves as a unidirectional heartbeat.  A response to an unsolicited Pong frame is not expected.
                        if let Err(reason) = (self.on_event)(Event::Pong(&msg)) {
                            let _ = self
                                .stream
                                .write_all(&CloseFrame::encode::<SIDE>(reason.to_string().as_str()))
                                .await;

                            err!(reason);
                        }
                    }
                    // 11-15 are reserved for further control frames
                    _ => err!(CloseEvent::Error("unknown opcode")),
                }
            } else {
                // Feature: client may intentionally sends consecutive fragment frames of size `0` ?
                // if !fin && len == 0 {
                //     return proto_err("Fragment length shouldn't be zero");
                // }
                let len = match len {
                    126 => u16::from_be_bytes(read_buf(&mut self.stream).await?) as usize,
                    127 => u64::from_be_bytes(read_buf(&mut self.stream).await?) as usize,
                    len => len,
                };
                return Ok((fin, opcode, len));
            }
        }
    }

    /// The FIN and opcode fields work together to send a message split up into separate frames. This is called message fragmentation.
    ///
    /// ```txt
    /// Client: FIN=1, opcode=0x1, msg="hello"
    /// Server: (process complete message immediately) Hi.
    /// Client: FIN=0, opcode=0x1, msg="and a"
    /// Server: (listening, new message containing text started)
    /// Client: FIN=0, opcode=0x0, msg="happy new"
    /// Server: (listening, payload concatenated to previous message)
    /// Client: FIN=1, opcode=0x0, msg="year!"
    /// Server: (process complete message) Happy new year to you too!
    /// ```
    ///
    /// ### Note
    ///
    /// - Control frames MAY be injected in the middle ofa fragmented message.
    ///   Control frames themselves MUST NOT be fragmented.
    ///   An endpoint MUST be capable of handling control frames in the middle of a fragmented message.
    #[inline]
    async fn read_fragmented_header(&mut self) -> Result<()> {
        let (fin, opcode, len) = self.header().await?;
        if opcode != 0 {
            err!(CloseEvent::Error("expected fragment frame"));
        }
        self.fin = fin;
        self.len = len;
        Ok(())
    }

    #[inline]
    async fn discard_old_data(&mut self) -> Result<()> {
        loop {
            if self.len > 0 {
                unsafe {
                    let mut discard = Vec::<u8>::with_capacity(self.len);
                    let uninit = std::slice::from_raw_parts_mut(discard.as_mut_ptr(), self.len);
                    let amt = self.stream.read(uninit).await?;
                    if amt == 0 {
                        err!(ConnectionAborted, "The connection was aborted");
                    }
                    self.len -= amt;
                }
                continue;
            }
            if self.fin {
                return Ok(());
            }
            self.read_fragmented_header().await?;
            // also skip masking keys sended from client
            if SERVER == SIDE {
                self.len += 4;
            }
        }
    }

    #[inline]
    async fn _recv(&mut self) -> Result<DataType> {
        self.discard_old_data().await?;

        let (fin, opcode, len) = self.header().await?;
        let data_type = match opcode {
            1 => DataType::Text,
            2 => DataType::Binary,
            _ => err!(CloseEvent::Error("expected data frame")),
        };
        self.fin = fin;
        self.len = len;
        Ok(data_type)
    }
}

macro_rules! cls_if_err {
    [$ws:expr, $code:expr] => ({
        if $ws.is_closed { err!(NotConnected, "read after close"); }
        match $code {
            Ok(val) => Ok(val),
            Err(err) => {
                $ws.is_closed = true;
                let _ = $ws.stream.flush().await;
                Err(err)
            }
        }
    });
}
macro_rules! read_exect {
    [$this:expr, $buf:expr, $code:expr] => {
        loop {
            match $this._read($buf).await? {
                0 => match $buf.is_empty() {
                    true => break,
                    false => $code,
                },
                amt => $buf = &mut $buf[amt..],
            }
        }
    };
}
macro_rules! default_impl_for_data {
    () => {
        impl<IO: Unpin + AsyncRead + AsyncWrite> Data<'_, IO> {
            /// Pull some bytes from this source into the specified buffer, returning how many bytes were read.
            #[inline]
            pub async fn read(&mut self, buf: &mut [u8]) -> Result<usize> {
                cls_if_err!(self.ws, {
                    if self.len() == 0 {
                        if self.ws.fin {
                            return Ok(0);
                        }
                        self._read_fragmented_header().await?;
                    }
                    self._read(buf).await
                })
            }

            /// Read the exact number of bytes required to fill buf.
            #[inline]
            pub async fn read_exact(&mut self, mut buf: &mut [u8]) -> Result<()> {
                cls_if_err!(self.ws, {
                    read_exect!(self, buf, {
                        if self.fin() {
                            err!(UnexpectedEof, "failed to fill whole buffer");
                        }
                        self._read_fragmented_header().await?;
                    });
                    Ok(())
                })
            }

            /// It is a wrapper around the [Self::read_to_end_with_limit] function with a default limit of `16` MB.
            #[inline]
            pub async fn read_to_end(&mut self, buf: &mut Vec<u8>) -> Result<()> {
                self.read_to_end_with_limit(buf, 16 * 1024 * 1024).await
            }

            /// Reads data until it reaches a specified limit or end of stream.
            pub async fn read_to_end_with_limit(
                &mut self,
                buf: &mut Vec<u8>,
                limit: usize,
            ) -> Result<()> {
                cls_if_err!(self.ws, {
                    let mut amt = 0;
                    loop {
                        let additional = self.len();
                        amt += additional;
                        if amt > limit {
                            err!(CloseEvent::Error("data read limit exceeded"));
                        }
                        unsafe {
                            buf.reserve(additional);
                            let len = buf.len();
                            let mut uninit = std::slice::from_raw_parts_mut(
                                buf.as_mut_ptr().add(len),
                                additional,
                            );
                            read_exect!(self, uninit, {
                                err!(UnexpectedEof, "failed to fill whole buffer");
                            });
                            buf.set_len(len + additional);
                        }
                        debug_assert!(self.len() == 0);
                        if self.fin() {
                            break Ok(());
                        }
                        self._read_fragmented_header().await?;
                    }
                })
            }
        }

        // Re-export
        impl<IO: Unpin + AsyncRead + AsyncWrite> Data<'_, IO> {
            /// Length of the "Payload data" in bytes.
            #[inline]
            #[allow(clippy::len_without_is_empty)]
            pub fn len(&self) -> usize {
                self.ws.len
            }

            /// Indicates that this is the final fragment in a message.  The first
            /// fragment MAY also be the final fragment.
            #[inline]
            pub fn fin(&self) -> bool {
                self.ws.fin
            }

            /// Flushes this output stream, ensuring that all intermediately buffered contents reach their destination.
            #[inline]
            pub async fn flash(&mut self) -> Result<()> {
                self.ws.stream.flush().await
            }

            /// send message to a endpoint by writing it to a WebSocket stream.
            #[inline]
            pub async fn send(&mut self, data: impl Message) -> Result<()> {
                self.ws.send(data).await
            }
        }
    };
}

pub(self) use cls_if_err;
pub(self) use default_impl_for_data;
pub(self) use read_exect;