forked from ninjasource/embedded-websocket
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathlib.rs
1627 lines (1475 loc) · 61.4 KB
/
lib.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
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
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
//! # Embedded Websocket
//!
//! `embedded_websocket` facilitates the encoding and decoding of websocket frames and can be used
//! for both clients and servers. The library is intended to be used in constrained memory
//! environments like embedded microcontrollers which cannot reference the rust standard library.
//! It will work with arbitrarily small buffers regardless of websocket frame size as long as the
//! websocket header can be read (2 - 14 bytes depending on the payload size and masking).
//! Since the library is essentially an encoder or decoder of byte slices, the developer is free to
//! use whatever transport mechanism they chose. The examples in the source repository use the
//! TcpStream from the standard library.
// support for websockets without using the standard library
#![cfg_attr(not(feature = "std"), no_std)]
use byteorder::{BigEndian, ByteOrder};
use core::{cmp, result, str};
use heapless::{String, Vec};
use rand_core::RngCore;
use sha1::{Digest, Sha1};
mod http;
pub mod random;
pub use self::http::{read_http_header, WebSocketContext};
pub use self::random::EmptyRng;
// support for working with discrete websocket frames when using IO streams
// start here!!
pub mod framer;
pub mod framer_async;
const MASK_KEY_LEN: usize = 4;
/// Result returning a websocket specific error if encountered
pub type Result<T> = result::Result<T, Error>;
/// A fixed length 24-character string used to hold a websocket key for the opening handshake
pub type WebSocketKey = String<24>;
/// A maximum sized 24-character string used to store a sub protocol (e.g. `chat`)
pub type WebSocketSubProtocol = String<24>;
/// Websocket send message type used when sending a websocket frame
#[derive(PartialEq, Eq, Debug, Copy, Clone)]
pub enum WebSocketSendMessageType {
/// A UTF8 encoded text string
Text = 1,
/// Binary data
Binary = 2,
/// An unsolicited ping message
Ping = 9,
/// A pong message in response to a ping message
Pong = 10,
/// A close message in response to a close message from the other party. Used to complete a
/// closing handshake. If initiate a close handshake use the `close` function
CloseReply = 11,
}
impl WebSocketSendMessageType {
fn to_op_code(self) -> WebSocketOpCode {
match self {
WebSocketSendMessageType::Text => WebSocketOpCode::TextFrame,
WebSocketSendMessageType::Binary => WebSocketOpCode::BinaryFrame,
WebSocketSendMessageType::Ping => WebSocketOpCode::Ping,
WebSocketSendMessageType::Pong => WebSocketOpCode::Pong,
WebSocketSendMessageType::CloseReply => WebSocketOpCode::ConnectionClose,
}
}
}
/// Websocket receive message type use when reading a websocket frame
#[derive(PartialEq, Eq, Debug, Copy, Clone)]
pub enum WebSocketReceiveMessageType {
/// A UTF8 encoded text string
Text = 1,
/// Binary data
Binary = 2,
/// Signals that the close handshake is complete
CloseCompleted = 7,
/// Signals that the other party has initiated the close handshake. If you receive this message
/// you should respond with a `WebSocketSendMessageType::CloseReply` with the same payload as
/// close message
CloseMustReply = 8,
/// A ping message that you should respond to with a `WebSocketSendMessageType::Pong` message
/// including the same payload as the ping
Ping = 9,
/// A pong message in response to a ping message
Pong = 10,
}
/// Websocket close status code as per the rfc6455 websocket spec
#[derive(PartialEq, Eq, Debug, Copy, Clone)]
pub enum WebSocketCloseStatusCode {
/// Normal closure (1000), meaning that the purpose for which the connection was established
/// has been fulfilled
NormalClosure,
/// Endpoint unavailable (1001) indicates that an endpoint is "going away", such as a server
/// going down or a browser having navigated away from a page
EndpointUnavailable,
/// Protocol error (1002) indicates that an endpoint is terminating the connection due
/// to a protocol error.
ProtocolError,
/// Invalid message type (1003) indicates that an endpoint is terminating the connection
/// because it has received a type of data it cannot accept (e.g., an endpoint that
/// understands only text data MAY send this if it receives a binary message)
InvalidMessageType,
/// Reserved (1004) for future use
Reserved,
/// Empty (1005) indicates that no status code was present
Empty,
/// Invalid payload data (1007) indicates that an endpoint is terminating the connection
/// because it has received data within a message that was not consistent with the type of
/// the message (e.g., non-UTF-8 data within a text message)
InvalidPayloadData,
/// Policy violation (1008) indicates that an endpoint is terminating the connection because
/// it has received a message that violates its policy. This is a generic status code that
/// can be returned when there is no other more suitable status code
PolicyViolation,
/// Message too big (1009) indicates that an endpoint is terminating the connection because
/// it has received a message that is too big for it to process
MessageTooBig,
/// Mandatory extension (1010) indicates that an endpoint (client) is terminating the
/// connection because it has expected the server to negotiate one or more extension, but
/// the server didn't return them in the response message of the WebSocket handshake
MandatoryExtension,
/// Internal server error (1011) indicates that a server is terminating the connection because
/// it encountered an unexpected condition that prevented it from fulfilling the request
InternalServerError,
/// TLS handshake (1015) connection was closed due to a failure to perform a TLS handshake
TlsHandshake,
/// Custom close code
Custom(u16),
}
impl WebSocketCloseStatusCode {
fn from_u16(value: u16) -> WebSocketCloseStatusCode {
match value {
1000 => WebSocketCloseStatusCode::NormalClosure,
1001 => WebSocketCloseStatusCode::EndpointUnavailable,
1002 => WebSocketCloseStatusCode::ProtocolError,
1003 => WebSocketCloseStatusCode::InvalidMessageType,
1004 => WebSocketCloseStatusCode::Reserved,
1005 => WebSocketCloseStatusCode::Empty,
1007 => WebSocketCloseStatusCode::InvalidPayloadData,
1008 => WebSocketCloseStatusCode::PolicyViolation,
1009 => WebSocketCloseStatusCode::MessageTooBig,
1010 => WebSocketCloseStatusCode::MandatoryExtension,
1011 => WebSocketCloseStatusCode::InternalServerError,
1015 => WebSocketCloseStatusCode::TlsHandshake,
_ => WebSocketCloseStatusCode::Custom(value),
}
}
fn to_u16(self) -> u16 {
match self {
WebSocketCloseStatusCode::NormalClosure => 1000,
WebSocketCloseStatusCode::EndpointUnavailable => 1001,
WebSocketCloseStatusCode::ProtocolError => 1002,
WebSocketCloseStatusCode::InvalidMessageType => 1003,
WebSocketCloseStatusCode::Reserved => 1004,
WebSocketCloseStatusCode::Empty => 1005,
WebSocketCloseStatusCode::InvalidPayloadData => 1007,
WebSocketCloseStatusCode::PolicyViolation => 1008,
WebSocketCloseStatusCode::MessageTooBig => 1009,
WebSocketCloseStatusCode::MandatoryExtension => 1010,
WebSocketCloseStatusCode::InternalServerError => 1011,
WebSocketCloseStatusCode::TlsHandshake => 1015,
WebSocketCloseStatusCode::Custom(value) => value,
}
}
}
/// The state of the websocket
#[derive(PartialEq, Eq, Copy, Clone, Debug)]
pub enum WebSocketState {
/// The websocket has been created with `new_client()` or `new_server()`
None = 0,
/// The client has created an opening handshake
Connecting = 1,
/// The server has completed the opening handshake via server_accept() or, likewise, the
/// client has completed the opening handshake via client_accept(). The user is free to call
/// `write()`, `read()` or `close()` on the websocket
Open = 2,
/// The `close()` function has been called
CloseSent = 3,
/// A Close websocket frame has been received
CloseReceived = 4,
/// The close handshake has been completed
Closed = 5,
/// The server or client opening handshake failed
Aborted = 6,
}
/// Websocket specific errors
#[derive(PartialEq, Eq, Debug)]
pub enum Error {
/// Websocket frame has an invalid opcode
InvalidOpCode,
InvalidFrameLength,
InvalidCloseStatusCode,
WebSocketNotOpen,
WebsocketAlreadyOpen,
Utf8Error,
Unknown,
HttpHeader(httparse::Error),
HttpHeaderNoPath,
HttpHeaderIncomplete,
WriteToBufferTooSmall,
ReadFrameIncomplete,
HttpResponseCodeInvalid(Option<u16>),
AcceptStringInvalid,
ConvertInfallible,
RandCore,
UnexpectedContinuationFrame,
}
impl From<httparse::Error> for Error {
fn from(err: httparse::Error) -> Error {
Error::HttpHeader(err)
}
}
impl From<str::Utf8Error> for Error {
fn from(_: str::Utf8Error) -> Error {
Error::Utf8Error
}
}
impl From<core::convert::Infallible> for Error {
fn from(_: core::convert::Infallible) -> Error {
Error::ConvertInfallible
}
}
impl From<()> for Error {
fn from(_: ()) -> Error {
Error::Unknown
}
}
impl core::fmt::Display for Error {
fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
match self {
Error::HttpHeader(error) => write!(f, "bad http header {error}"),
Error::HttpResponseCodeInvalid(Some(code)) => write!(f, "bad http response ({code})"),
_ => write!(f, "{:?}", self),
}
}
}
#[cfg(feature = "std")]
impl std::error::Error for Error {
fn source(&self) -> Option<&(dyn std::error::Error + 'static)> {
if let Self::HttpHeader(error) = self {
Some(error)
} else {
None
}
}
}
#[derive(Copy, Clone, Debug, PartialEq, Eq)]
enum WebSocketOpCode {
ContinuationFrame = 0,
TextFrame = 1,
BinaryFrame = 2,
ConnectionClose = 8,
Ping = 9,
Pong = 10,
}
impl WebSocketOpCode {
fn to_message_type(self) -> Result<WebSocketReceiveMessageType> {
match self {
WebSocketOpCode::TextFrame => Ok(WebSocketReceiveMessageType::Text),
WebSocketOpCode::BinaryFrame => Ok(WebSocketReceiveMessageType::Binary),
_ => Err(Error::InvalidOpCode),
}
}
}
/// The metadata result of a `read` function call of a websocket
#[derive(Debug)]
pub struct WebSocketReadResult {
/// Number of bytes read from the `from` buffer
pub len_from: usize,
/// Number of bytes written to the `to` buffer
pub len_to: usize,
/// End of message flag is `true` if the `to` buffer contains an entire websocket frame
/// payload otherwise `false` if the user must continue calling the read function to get the
/// rest of the payload
pub end_of_message: bool,
/// Close status code (as per the websocket spec) if the message type is `CloseMustReply` or
/// `CloseCompleted`. If a close status is specified then a UTF8 encoded string could also
/// appear in the frame payload giving more detailed information about why the websocket was
/// closed.
pub close_status: Option<WebSocketCloseStatusCode>,
/// The websocket frame type
pub message_type: WebSocketReceiveMessageType,
}
/// Websocket options used by a websocket client to initiate an opening handshake with a
/// websocket server
pub struct WebSocketOptions<'a> {
/// The request uri (e.g. `/chat?id=123`) of the GET method used to identify the endpoint of the
/// websocket connection. This allows multiple domains to be served by a single server.
/// This could also be used to send identifiable information about the client
pub path: &'a str,
/// The hostname (e.g. `server.example.com`) is used so that both the client and the server
/// can verify that they agree on which host is in use
pub host: &'a str,
/// The origin (e.g. `http://example.com`) is used to protect against unauthorized
/// cross-origin use of a WebSocket server by scripts using the WebSocket API in a web
/// browser. This field is usually only set by browser clients but servers may require it
/// so it has been exposed here.
pub origin: &'a str,
/// A list of requested sub protocols in order of preference. The server should return the
/// first sub protocol it supports or none at all. A sub protocol can be anything agreed
/// between the server and client
pub sub_protocols: Option<&'a [&'a str]>,
/// Any additional headers the server may require that are not part of the websocket
/// spec. These should be fully formed http headers without the `\r\n` (e.g. `MyHeader: foo`)
pub additional_headers: Option<&'a [&'a str]>,
}
/// Used to return a sized type from `WebSocket::new_server()`
pub type WebSocketServer = WebSocket<EmptyRng, Server>;
/// Used to return a sized type from `WebSocketClient::new_client()`
pub type WebSocketClient<T> = WebSocket<T, Client>;
// Simple Typestate pattern for preventing panics and allowing reuse of underlying
// read/read_frame/etc..
pub enum Server {}
pub enum Client {}
pub trait WebSocketType {}
impl WebSocketType for Server {}
impl WebSocketType for Client {}
/// Websocket client and server implementation
pub struct WebSocket<T, S: WebSocketType>
where
T: RngCore,
{
is_client: bool,
rng: T,
continuation_frame_op_code: Option<WebSocketOpCode>,
is_write_continuation: bool,
pub state: WebSocketState,
continuation_read: Option<ContinuationRead>,
marker: core::marker::PhantomData<S>,
}
impl<T, Type> WebSocket<T, Type>
where
T: RngCore,
Type: WebSocketType,
{
/// Creates a new websocket client by passing in a required random number generator
///
/// # Examples
/// ```
/// use embedded_websocket as ws;
/// use rand;
/// let mut ws_client = ws::WebSocketClient::new_client(rand::thread_rng());
///
/// assert_eq!(ws::WebSocketState::None, ws_client.state);
/// ```
pub fn new_client(rng: T) -> WebSocketClient<T> {
WebSocket {
is_client: true,
rng,
continuation_frame_op_code: None,
is_write_continuation: false,
state: WebSocketState::None,
continuation_read: None,
marker: core::marker::PhantomData::<Client>,
}
}
/// Creates a new websocket server. Note that you must use the `WebSocketServer` type and
/// not the generic `WebSocket` type for this call or you will get a `'type annotations needed'`
/// compilation error.
///
/// # Examples
/// ```
/// use embedded_websocket as ws;
/// let mut ws_server = ws::WebSocketServer::new_server();
///
/// assert_eq!(ws::WebSocketState::None, ws_server.state);
/// ```
pub fn new_server() -> WebSocketServer {
let rng = EmptyRng::new();
WebSocket {
is_client: false,
rng,
continuation_frame_op_code: None,
is_write_continuation: false,
state: WebSocketState::None,
continuation_read: None,
marker: core::marker::PhantomData::<Server>,
}
}
}
impl<T> WebSocket<T, Server>
where
T: RngCore,
{
/// Used by the server to accept an incoming client connection and build a websocket upgrade
/// http response string. The client http header should be read with the `read_http_header`
/// function and the result should be passed to this function.
/// Websocket state will change from None -> Open if successful, otherwise None -> Aborted
///
/// # Examples
///
/// ```
/// use embedded_websocket as ws;
/// let mut buffer: [u8; 1000] = [0; 1000];
/// let mut ws_server = ws::WebSocketServer::new_server();
/// let ws_key = ws::WebSocketKey::from("Z7OY1UwHOx/nkSz38kfPwg==");
/// let sub_protocol = ws::WebSocketSubProtocol::from("chat");
/// let len = ws_server
/// .server_accept(&ws_key, Some(&sub_protocol), &mut buffer)
/// .unwrap();
/// let response = std::str::from_utf8(&buffer[..len]).unwrap();
///
/// assert_eq!("HTTP/1.1 101 Switching Protocols\r\nConnection: Upgrade\r\nUpgrade: websocket\r\nSec-WebSocket-Protocol: chat\r\nSec-WebSocket-Accept: ptPnPeDOTo6khJlzmLhOZSh2tAY=\r\n\r\n", response);
/// ```
///
/// # Errors
/// There should be no way for a user provided input to return the errors listed below as the
/// input is already constrained.
/// * The http response is built with a stack allocated 1KB buffer and it *should be impossible*
/// for it to return an `Unknown` error if that buffer is too small. However, this is better
/// than a panic and it will do so if the response header is too large to fit in the buffer
/// * This function can return an `Utf8Error` if there was an error with the generation of the
/// accept string. This should also be impossible but an error is preferable to a panic
/// * Returns `WebsocketAlreadyOpen` if called on a websocket that is already open
pub fn server_accept(
&mut self,
sec_websocket_key: &WebSocketKey,
sec_websocket_protocol: Option<&WebSocketSubProtocol>,
to: &mut [u8],
) -> Result<usize> {
if self.state == WebSocketState::Open {
return Err(Error::WebsocketAlreadyOpen);
}
match http::build_connect_handshake_response(sec_websocket_key, sec_websocket_protocol, to)
{
Ok(http_response_len) => {
self.state = WebSocketState::Open;
Ok(http_response_len)
}
Err(e) => {
self.state = WebSocketState::Aborted;
Err(e)
}
}
}
}
impl<T> WebSocket<T, Client>
where
T: RngCore,
{
/// Used by the client to initiate a websocket opening handshake
///
/// # Examples
/// ```
/// use embedded_websocket as ws;
/// let mut buffer: [u8; 2000] = [0; 2000];
/// let mut ws_client = ws::WebSocketClient::new_client(rand::thread_rng());
/// let sub_protocols = ["chat", "superchat"];
/// let websocket_options = ws::WebSocketOptions {
/// path: "/chat",
/// host: "localhost",
/// origin: "http://localhost",
/// sub_protocols: Some(&sub_protocols),
/// additional_headers: None,
/// };
///
/// let (len, web_socket_key) = ws_client.client_connect(&websocket_options, &mut buffer).unwrap();
///
/// let actual_http = std::str::from_utf8(&buffer[..len]).unwrap();
/// let mut expected_http = String::new();
/// expected_http.push_str("GET /chat HTTP/1.1\r\nHost: localhost\r\nUpgrade: websocket\r\nConnection: Upgrade\r\nSec-WebSocket-Key: ");
/// expected_http.push_str(web_socket_key.as_str());
/// expected_http.push_str("\r\nOrigin: http://localhost\r\nSec-WebSocket-Protocol: chat, superchat\r\nSec-WebSocket-Version: 13\r\n\r\n");
/// assert_eq!(expected_http.as_str(), actual_http);
/// ```
///
/// # Errors
/// * The http response is built with a stack allocated 1KB buffer and will return an
/// `Unknown` error if that buffer is too small. This would happen is the user supplied too many
/// additional headers or the sub-protocol string is too large
/// * This function can return an `Utf8Error` if there was an error with the generation of the
/// accept string. This should be impossible but an error is preferable to a panic
/// * Returns `WebsocketAlreadyOpen` if called on a websocket that is already open
pub fn client_connect(
&mut self,
websocket_options: &WebSocketOptions,
to: &mut [u8],
) -> Result<(usize, WebSocketKey)> {
if self.state == WebSocketState::Open {
return Err(Error::WebsocketAlreadyOpen);
}
match http::build_connect_handshake_request(websocket_options, &mut self.rng, to) {
Ok((request_len, sec_websocket_key)) => {
self.state = WebSocketState::Connecting;
Ok((request_len, sec_websocket_key))
}
Err(e) => Err(e),
}
}
/// Used by a websocket client for checking the server response to an opening handshake
/// (sent using the client_connect function). If the client requested one or more sub protocols
/// the server will choose one (or none) and you get that in the result
/// # Examples
/// ```
/// use embedded_websocket as ws;
/// let mut ws_client = ws::WebSocketClient::new_client(rand::thread_rng());
/// let ws_key = ws::WebSocketKey::from("Z7OY1UwHOx/nkSz38kfPwg==");
/// let server_response_html = "HTTP/1.1 101 Switching Protocols\r\nConnection: Upgrade\r\nUpgrade: websocket\r\nSec-WebSocket-Protocol: chat\r\nSec-WebSocket-Accept: ptPnPeDOTo6khJlzmLhOZSh2tAY=\r\n\r\n"; ///
/// let (len, sub_protocol) = ws_client.client_accept(&ws_key, server_response_html.as_bytes())
/// .unwrap();
///
/// assert_eq!(159, len);
/// assert_eq!("chat", sub_protocol.unwrap());
/// ```
/// # Errors
/// * Returns `HttpResponseCodeInvalid` if the HTTP response code is not `101 Switching Protocols`
/// * Returns `AcceptStringInvalid` if the web server failed to return a valid accept string
/// * Returns `HttpHeader(Version)` or some other varient if the HTTP response is not well formed
/// * Returns `WebsocketAlreadyOpen` if called on a websocket that is already open
pub fn client_accept(
&mut self,
sec_websocket_key: &WebSocketKey,
from: &[u8],
) -> Result<(usize, Option<WebSocketSubProtocol>)> {
if self.state == WebSocketState::Open {
return Err(Error::WebsocketAlreadyOpen);
}
match http::read_server_connect_handshake_response(sec_websocket_key, from) {
Ok((len, sec_websocket_protocol)) => {
self.state = WebSocketState::Open;
Ok((len, sec_websocket_protocol))
}
Err(Error::HttpHeaderIncomplete) => Err(Error::HttpHeaderIncomplete),
Err(e) => {
self.state = WebSocketState::Aborted;
Err(e)
}
}
}
}
impl<T, Type> WebSocket<T, Type>
where
T: RngCore,
Type: WebSocketType,
{
/// Reads the payload from a websocket frame in buffer `from` into a buffer `to` and returns
/// metadata about the frame. Since this function is designed to be called in a memory
/// constrained system we may not read the entire payload in one go. In each of the scenarios
/// below the `read_result.end_of_message` flag would be `false`:
/// * The payload is fragmented into multiple websocket frames (as per the websocket spec)
/// * The `from` buffer does not hold the entire websocket frame. For example if only part of
/// the frame was read or if the `from` buffer is too small to hold an entire websocket frame
/// * The `to` buffer is too small to hold the entire websocket frame payload
///
/// If the function returns `read_result.end_of_message` `false` then the next
/// call to the function should not include data that has already been passed into the function.
/// The websocket *remembers* the websocket frame header and is able to process the rest of the
/// payload correctly. If the `from` buffer contains multiple websocket frames then only one of
/// them will be returned at a time and the user must make multiple calls to the function by
/// taking note of `read_result.len_from` which tells you how many bytes were read from the
/// `from` buffer
///
/// # Examples
///
/// ```
/// use embedded_websocket as ws;
/// // h e l l o
/// let buffer1 = [129,5,104,101,108,108,111];
/// let mut buffer2: [u8; 128] = [0; 128];
/// let mut ws_client = ws::WebSocketClient::new_client(rand::thread_rng());
/// ws_client.state = ws::WebSocketState::Open; // skip the opening handshake
/// let ws_result = ws_client.read(&buffer1, &mut buffer2).unwrap();
///
/// assert_eq!("hello".as_bytes(), &buffer2[..ws_result.len_to]);
/// ```
/// # Errors
/// * Returns `WebSocketNotOpen` when the websocket is not open when this function is called
/// * Returns `InvalidOpCode` if the websocket frame contains an invalid opcode
/// * Returns `UnexpectedContinuationFrame` if we receive a continuation frame without first
/// receiving a non-continuation frame with an opcode describing the payload
/// * Returns `ReadFrameIncomplete` if the `from` buffer does not contain a full websocket
/// header (typically 2-14 bytes depending on the payload)
/// * Returns `InvalidFrameLength` if the frame length cannot be decoded
///
pub fn read(&mut self, from: &[u8], to: &mut [u8]) -> Result<WebSocketReadResult> {
if self.state == WebSocketState::Open || self.state == WebSocketState::CloseSent {
let frame = self.read_frame(from, to)?;
match frame.op_code {
WebSocketOpCode::Ping => Ok(frame.to_readresult(WebSocketReceiveMessageType::Ping)),
WebSocketOpCode::Pong => Ok(frame.to_readresult(WebSocketReceiveMessageType::Pong)),
WebSocketOpCode::TextFrame => {
Ok(frame.to_readresult(WebSocketReceiveMessageType::Text))
}
WebSocketOpCode::BinaryFrame => {
Ok(frame.to_readresult(WebSocketReceiveMessageType::Binary))
}
WebSocketOpCode::ConnectionClose => match self.state {
WebSocketState::CloseSent => {
self.state = WebSocketState::Closed;
Ok(frame.to_readresult(WebSocketReceiveMessageType::CloseCompleted))
}
_ => {
self.state = WebSocketState::CloseReceived;
Ok(frame.to_readresult(WebSocketReceiveMessageType::CloseMustReply))
}
},
WebSocketOpCode::ContinuationFrame => match self.continuation_frame_op_code {
Some(cf_op_code) => Ok(frame.to_readresult(cf_op_code.to_message_type()?)),
None => Err(Error::UnexpectedContinuationFrame),
},
}
} else {
Err(Error::WebSocketNotOpen)
}
}
/// Writes the payload in `from` to a websocket frame in `to`
/// * message_type - The type of message to send: Text, Binary or CloseReply
/// * end_of_message - False to fragment a frame into multiple smaller frames. The last frame
/// should set this to true
/// * from - The buffer containing the payload to encode
/// * to - The the buffer to save the websocket encoded payload to.
/// Returns the number of bytes written to the `to` buffer
/// # Examples
///
/// ```
/// use embedded_websocket as ws;
/// let mut buffer: [u8; 1000] = [0; 1000];
/// let mut ws_server = ws::WebSocketServer::new_server();
/// ws_server.state = ws::WebSocketState::Open; // skip the opening handshake
/// let len = ws_server.write(ws::WebSocketSendMessageType::Text, true, "hello".as_bytes(),
/// &mut buffer).unwrap();
///
/// // h e l l o
/// let expected = [129,5,104,101,108,108,111];
/// assert_eq!(&expected, &buffer[..len]);
/// ```
/// # Errors
/// * Returns `WebSocketNotOpen` when the websocket is not open when this function is called
/// * Returns `WriteToBufferTooSmall` when the `to` buffer is too small to fit the websocket
/// frame header (2-14 bytes) plus the payload. Consider fragmenting the messages by making
/// multiple write calls with `end_of_message` set to `false` and the final call set to `true`
pub fn write(
&mut self,
message_type: WebSocketSendMessageType,
end_of_message: bool,
from: &[u8],
to: &mut [u8],
) -> Result<usize> {
if self.state == WebSocketState::Open || self.state == WebSocketState::CloseReceived {
let mut op_code = message_type.to_op_code();
if op_code == WebSocketOpCode::ConnectionClose {
self.state = WebSocketState::Closed
} else if self.is_write_continuation {
op_code = WebSocketOpCode::ContinuationFrame;
}
self.is_write_continuation = !end_of_message;
self.write_frame(from, to, op_code, end_of_message)
} else {
Err(Error::WebSocketNotOpen)
}
}
/// Initiates a close handshake.
/// Both the client and server may initiate a close handshake. If successful the function
/// changes the websocket state from Open -> CloseSent
/// # Errors
/// * Returns `WebSocketNotOpen` when the websocket is not open when this function is called
/// * Returns `WriteToBufferTooSmall` when the `to` buffer is too small to fit the websocket
/// frame header (2-14 bytes) plus the payload. Consider sending a smaller status_description
pub fn close(
&mut self,
close_status: WebSocketCloseStatusCode,
status_description: Option<&str>,
to: &mut [u8],
) -> Result<usize> {
if self.state == WebSocketState::Open {
self.state = WebSocketState::CloseSent;
if let Some(status_description) = status_description {
let mut from_buffer: Vec<u8, 256> = Vec::new();
from_buffer.extend_from_slice(&close_status.to_u16().to_be_bytes())?;
// restrict the max size of the status_description
let len = if status_description.len() < 254 {
status_description.len()
} else {
254
};
from_buffer.extend_from_slice(status_description[..len].as_bytes())?;
self.write_frame(&from_buffer, to, WebSocketOpCode::ConnectionClose, true)
} else {
let mut from_buffer: [u8; 2] = [0; 2];
BigEndian::write_u16(&mut from_buffer, close_status.to_u16());
self.write_frame(&from_buffer, to, WebSocketOpCode::ConnectionClose, true)
}
} else {
Err(Error::WebSocketNotOpen)
}
}
fn read_frame(&mut self, from_buffer: &[u8], to_buffer: &mut [u8]) -> Result<WebSocketFrame> {
match &mut self.continuation_read {
Some(continuation_read) => {
let result = read_continuation(continuation_read, from_buffer, to_buffer);
if continuation_read.count == 0 {
self.continuation_read = None;
}
if result.is_fin_bit_set {
self.continuation_read = None;
self.continuation_frame_op_code = None;
}
Ok(result)
}
None => {
let (mut result, mut continuation_read) = read_frame(from_buffer, to_buffer)?;
// override the op code we get from the result with our continuation frame opcode if it exists
if let Some(continuation_frame_op_code) = self.continuation_frame_op_code {
result.op_code = continuation_frame_op_code;
if let Some(continuation) = &mut continuation_read {
continuation.op_code = continuation_frame_op_code;
}
}
// reset the continuation frame op code to None if this is the last fragment (or there is no fragmentation)
self.continuation_frame_op_code = if result.is_fin_bit_set {
None
} else {
Some(result.op_code)
};
self.continuation_read = continuation_read;
Ok(result)
}
}
}
fn write_frame(
&mut self,
from_buffer: &[u8],
to_buffer: &mut [u8],
op_code: WebSocketOpCode,
end_of_message: bool,
) -> Result<usize> {
let fin_bit_set_as_byte: u8 = if end_of_message { 0x80 } else { 0x00 };
let byte1: u8 = fin_bit_set_as_byte | op_code as u8;
let count = from_buffer.len();
const BYTE_HEADER_SIZE: usize = 2;
const SHORT_HEADER_SIZE: usize = 4;
const LONG_HEADER_SIZE: usize = 10;
const MASK_KEY_SIZE: usize = 4;
let header_size;
let mask_bit_set_as_byte = if self.is_client { 0x80 } else { 0x00 };
let payload_len = from_buffer.len() + if self.is_client { MASK_KEY_SIZE } else { 0 };
// write header followed by the payload
// header size depends on how large the payload is
if count < 126 {
if payload_len + BYTE_HEADER_SIZE > to_buffer.len() {
return Err(Error::WriteToBufferTooSmall);
}
to_buffer[0] = byte1;
to_buffer[1] = mask_bit_set_as_byte | count as u8;
header_size = BYTE_HEADER_SIZE;
} else if count < 65535 {
if payload_len + SHORT_HEADER_SIZE > to_buffer.len() {
return Err(Error::WriteToBufferTooSmall);
}
to_buffer[0] = byte1;
to_buffer[1] = mask_bit_set_as_byte | 126;
BigEndian::write_u16(&mut to_buffer[2..], count as u16);
header_size = SHORT_HEADER_SIZE;
} else {
if payload_len + LONG_HEADER_SIZE > to_buffer.len() {
return Err(Error::WriteToBufferTooSmall);
}
to_buffer[0] = byte1;
to_buffer[1] = mask_bit_set_as_byte | 127;
BigEndian::write_u64(&mut to_buffer[2..], count as u64);
header_size = LONG_HEADER_SIZE;
}
// sent by client - need to mask the data
// we need to mask the bytes to prevent web server caching
if self.is_client {
let mut mask_key = [0; MASK_KEY_SIZE];
self.rng.fill_bytes(&mut mask_key); // clients always have an rng instance
to_buffer[header_size..header_size + MASK_KEY_SIZE].copy_from_slice(&mask_key);
let to_buffer_start = header_size + MASK_KEY_SIZE;
// apply the mask key to every byte in the payload. This is a hot function
for (i, (from, to)) in from_buffer[..count]
.iter()
.zip(&mut to_buffer[to_buffer_start..to_buffer_start + count])
.enumerate()
{
*to = *from ^ mask_key[i % MASK_KEY_SIZE];
}
Ok(to_buffer_start + count)
} else {
to_buffer[header_size..header_size + count].copy_from_slice(&from_buffer[..count]);
Ok(header_size + count)
}
}
}
// Continuation read is used when we cannot fit the entire websocket frame into the supplied buffer
struct ContinuationRead {
op_code: WebSocketOpCode,
count: usize,
is_fin_bit_set: bool,
mask_key: Option<[u8; 4]>,
}
struct WebSocketFrame {
is_fin_bit_set: bool,
op_code: WebSocketOpCode,
num_bytes_to: usize,
num_bytes_from: usize,
close_status: Option<WebSocketCloseStatusCode>,
}
impl WebSocketFrame {
fn to_readresult(&self, message_type: WebSocketReceiveMessageType) -> WebSocketReadResult {
WebSocketReadResult {
len_from: self.num_bytes_from,
len_to: self.num_bytes_to,
end_of_message: self.is_fin_bit_set,
close_status: self.close_status,
message_type,
}
}
}
fn min(num1: usize, num2: usize, num3: usize) -> usize {
cmp::min(cmp::min(num1, num2), num3)
}
fn read_into_buffer(
mask_key: &mut Option<[u8; 4]>,
from_buffer: &[u8],
to_buffer: &mut [u8],
len: usize,
) -> usize {
// if we are trying to read more than number of bytes in either buffer
let len_to_read = min(len, to_buffer.len(), from_buffer.len());
match mask_key {
Some(mask_key) => {
// apply the mask key to every byte in the payload. This is a hot function.
for (i, (from, to)) in from_buffer[..len_to_read].iter().zip(to_buffer).enumerate() {
*to = *from ^ mask_key[i % MASK_KEY_LEN];
}
mask_key.rotate_left(len_to_read % MASK_KEY_LEN);
}
None => {
to_buffer[..len_to_read].copy_from_slice(&from_buffer[..len_to_read]);
}
}
len_to_read
}
fn read_continuation(
continuation_read: &mut ContinuationRead,
from_buffer: &[u8],
to_buffer: &mut [u8],
) -> WebSocketFrame {
let len_read = read_into_buffer(
&mut continuation_read.mask_key,
from_buffer,
to_buffer,
continuation_read.count,
);
let is_complete = len_read == continuation_read.count;
let frame = match continuation_read.op_code {
WebSocketOpCode::ConnectionClose => decode_close_frame(to_buffer, len_read, len_read),
_ => WebSocketFrame {
num_bytes_from: len_read,
num_bytes_to: len_read,
op_code: continuation_read.op_code,
close_status: None,
is_fin_bit_set: if is_complete {
continuation_read.is_fin_bit_set
} else {
false
},
},
};
continuation_read.count -= len_read;
frame
}
fn read_frame(
from_buffer: &[u8],
to_buffer: &mut [u8],
) -> Result<(WebSocketFrame, Option<ContinuationRead>)> {
if from_buffer.len() < 2 {
return Err(Error::ReadFrameIncomplete);
}
let byte1 = from_buffer[0];
let byte2 = from_buffer[1];
// process first byte
const FIN_BIT_FLAG: u8 = 0x80;
const OP_CODE_FLAG: u8 = 0x0F;
let is_fin_bit_set = (byte1 & FIN_BIT_FLAG) == FIN_BIT_FLAG;
let op_code = get_op_code(byte1 & OP_CODE_FLAG)?;
// process second byte
const MASK_FLAG: u8 = 0x80;
let is_mask_bit_set = (byte2 & MASK_FLAG) == MASK_FLAG;
let (len, mut num_bytes_read) = read_length(byte2, &from_buffer[2..])?;
num_bytes_read += 2;
let from_buffer = &from_buffer[num_bytes_read..];
// reads the mask key from the payload if the is_mask_bit_set flag is set
let mut mask_key = if is_mask_bit_set {
if from_buffer.len() < MASK_KEY_LEN {
return Err(Error::ReadFrameIncomplete);
}
let mut mask_key: [u8; MASK_KEY_LEN] = [0; MASK_KEY_LEN];
mask_key.copy_from_slice(&from_buffer[..MASK_KEY_LEN]);
num_bytes_read += MASK_KEY_LEN;
Some(mask_key)
} else {
None
};
let len_read = if is_mask_bit_set {
// start after the mask key
let from_buffer = &from_buffer[MASK_KEY_LEN..];
read_into_buffer(&mut mask_key, from_buffer, to_buffer, len)
} else {
read_into_buffer(&mut mask_key, from_buffer, to_buffer, len)
};
let has_continuation = len_read < len;
num_bytes_read += len_read;
let frame = match op_code {
WebSocketOpCode::ConnectionClose => decode_close_frame(to_buffer, num_bytes_read, len_read),
_ => WebSocketFrame {
num_bytes_from: num_bytes_read,
num_bytes_to: len_read,
op_code,
close_status: None,
is_fin_bit_set: if has_continuation {
false
} else {
is_fin_bit_set
},
},
};
if has_continuation {
let continuation_read = Some(ContinuationRead {
op_code,
count: len - len_read,
is_fin_bit_set,
mask_key,
});
Ok((frame, continuation_read))
} else {
Ok((frame, None))
}
}
fn get_op_code(val: u8) -> Result<WebSocketOpCode> {
match val {
0 => Ok(WebSocketOpCode::ContinuationFrame),
1 => Ok(WebSocketOpCode::TextFrame),