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
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
//! # 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). </p>
//! 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.

#![no_std]

use byteorder::{BigEndian, ByteOrder, LittleEndian};
use core::{cmp, result, str};
use heapless::consts::*; // these are for constants like U4, U16, U24, U32
use heapless::{String, Vec};
use rand_core::RngCore;
use sha1::Sha1;

mod base64;
mod http;
mod random;
pub use self::http::{read_http_header, HttpHeader, WebSocketContext};
use random::EmptyRng;

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<U24>;

/// A maximum sized 24-character string used to store a sub protocol (e.g. `chat`)
pub type WebSocketSubProtocol = String<U24>;

/// Websocket send message type used when sending a websocket frame
#[derive(PartialEq, 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, 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, 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, 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, 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,
    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
    }
}

#[derive(Copy, Clone, Debug, PartialEq)]
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>;

/// Websocket client and server implementation
pub struct WebSocket<T>
where
    T: RngCore,
{
    is_client: bool,
    rng: T,
    continuation_frame_op_code: Option<WebSocketOpCode>,
    pub state: WebSocketState,
    continuation_read: Option<ContinuationRead>,
}

impl<T> WebSocket<T>
where
    T: RngCore,
{
    /// 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::WebSocket::new_client(rand::thread_rng());
    ///
    /// assert_eq!(ws::WebSocketState::None, ws_client.state);
    /// ```
    pub fn new_client(rng: T) -> WebSocket<T> {
        WebSocket {
            is_client: true,
            rng,
            continuation_frame_op_code: None,
            state: WebSocketState::None,
            continuation_read: None,
        }
    }

    /// 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,
            state: WebSocketState::None,
            continuation_read: None,
        }
    }

    /// 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. </p>
    /// 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
    ///
    /// # Panics
    /// Panics with `Server websocket expected` if the user calls this function as a client
    /// websocket. This function should be use with a websocket created using `new_server()`
    pub fn server_accept(
        &mut self,
        sec_websocket_key: &WebSocketKey,
        sec_websocket_protocol: Option<&WebSocketSubProtocol>,
        to: &mut [u8],
    ) -> Result<usize> {
        if self.is_client {
            panic!("Server websocket expected");
        }
        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)
            }
        }
    }

    /// 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::WebSocket::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
    ///
    /// # Panics
    /// Panics with `Client websocket expected` if the user calls this function as a server
    /// websocket. This function should be use with a websocket created using `new_client()`
    pub fn client_connect(
        &mut self,
        websocket_options: &WebSocketOptions,
        to: &mut [u8],
    ) -> Result<(usize, WebSocketKey)> {
        if !self.is_client {
            panic!("Client websocket expected");
        }
        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::WebSocket::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 (sub_protocol) = ws_client.client_accept(&ws_key, server_response_html.as_bytes())
    ///     .unwrap();
    ///
    /// 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
    /// # Panics
    /// Panics with `Client websocket expected` if the user calls this function as a server
    /// websocket. This function should be use with a websocket created using `new_client()`
    pub fn client_accept(
        &mut self,
        sec_websocket_key: &WebSocketKey,
        from: &[u8],
    ) -> Result<Option<WebSocketSubProtocol>> {
        if !self.is_client {
            panic!("Client websocket expected");
        }
        if self.state == WebSocketState::Open {
            return Err(Error::WebsocketAlreadyOpen);
        }

        match http::read_server_connect_handshake_response(sec_websocket_key, from) {
            Ok(sec_websocket_protocol) => {
                self.state = WebSocketState::Open;
                Ok(sec_websocket_protocol)
            }
            Err(e) => {
                self.state = WebSocketState::Aborted;
                Err(e)
            }
        }
    }

    /// Reads the payload from a websocket frame in buffer `from` into a buffer `to` and returns
    /// metadata about the frame. </p>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::WebSocket::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 op_code = message_type.to_op_code();
            if op_code == WebSocketOpCode::ConnectionClose {
                self.state = WebSocketState::Closed
            }

            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, U256> = Vec::new();
                BigEndian::write_u16(&mut from_buffer, close_status.to_u16());

                // restrict the max size of the status_description
                let len = if status_description.len() < 254 {
                    status_description.len()
                } else {
                    254
                };

                from_buffer.extend(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 result.is_fin_bit_set {
                    self.continuation_read = None;
                }
                Ok(result)
            }
            None => {
                let (result, continuation_read) = read_frame(from_buffer, to_buffer)?;
                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;
            LittleEndian::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;
            LittleEndian::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;

            let mut i = 0;
            // apply the mask key to every byte in the payload. This is a hot function
            for (from, to) in from_buffer[..count]
                .iter()
                .zip(&mut to_buffer[to_buffer_start..to_buffer_start + count])
            {
                *to = *from ^ mask_key[i % MASK_KEY_SIZE];
                i = i + 1;
            }

            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: 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) => {
            let mut i = 0;
            // apply the mask key to every byte in the payload. This is a hot function.
            for (from, to) in from_buffer[..len_to_read].iter().zip(to_buffer) {
                *to = *from ^ mask_key[i % MASK_KEY_LEN];
                i = i + 1;
            }
        }
        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(
        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 = 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 = 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 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 = 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(mask_key, from_buffer, to_buffer, len)
    } else {
        read_into_buffer(mask_key, from_buffer, to_buffer, len)
    };

    let has_continuation = len_read < len;
    num_bytes_read = 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),
        2 => Ok(WebSocketOpCode::BinaryFrame),
        8 => Ok(WebSocketOpCode::ConnectionClose),
        9 => Ok(WebSocketOpCode::Ping),
        10 => Ok(WebSocketOpCode::Pong),
        _ => Err(Error::InvalidOpCode),
    }
}

// returns (len, how_many_bytes_were_read)
fn read_length(byte2: u8, from_buffer: &[u8]) -> Result<(usize, usize)> {
    let len = byte2 & 0x7F;

    if len < 126 {
        // for messages smaller than 126 bytes
        return Ok((len as usize, 0));
    } else if len == 126 {
        // for messages smaller than 64KB
        if from_buffer.len() < 2 {
            return Err(Error::ReadFrameIncomplete);
        }
        let mut buf: [u8; 2] = [0; 2];
        buf.copy_from_slice(&from_buffer[..2]);
        return Ok((BigEndian::read_u16(&buf) as usize, 2));
    } else if len == 127 {
        // for messages larger than 64KB
        if from_buffer.len() < 8 {
            return Err(Error::ReadFrameIncomplete);
        }
        let mut buf: [u8; 8] = [0; 8];
        buf.copy_from_slice(&from_buffer[..8]);
        return Ok((BigEndian::read_u64(&buf) as usize, 8));
    }

    Err(Error::InvalidFrameLength)
}

fn decode_close_frame(buffer: &mut [u8], num_bytes_read: usize, len: usize) -> WebSocketFrame {
    if len >= 2 {
        // NOTE: for now, don't read the close status description
        let code = BigEndian::read_u16(buffer);
        let close_status_code = WebSocketCloseStatusCode::from_u16(code);

        return WebSocketFrame {
            num_bytes_from: num_bytes_read,
            num_bytes_to: len,
            op_code: WebSocketOpCode::ConnectionClose,
            close_status: Some(close_status_code),
            is_fin_bit_set: true,
        };
    }

    build_client_disconnected_frame(num_bytes_read)
}

fn build_client_disconnected_frame(num_bytes_from: usize) -> WebSocketFrame {
    WebSocketFrame {
        num_bytes_from,
        num_bytes_to: 0,
        op_code: WebSocketOpCode::ConnectionClose,
        close_status: Some(WebSocketCloseStatusCode::InternalServerError),
        is_fin_bit_set: true,
    }
}

// ************************************************************************************************
// **************************************** TESTS *************************************************
// ************************************************************************************************

#[cfg(test)]
mod tests {
    extern crate std;
    use super::*;

    #[test]
    fn opening_handshake() {
        let client_request = "GET /chat HTTP/1.1
Host: localhost:5000
User-Agent: Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:62.0) Gecko/20100101 Firefox/62.0
Accept: text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8
Accept-Language: en-US,en;q=0.5
Accept-Encoding: gzip, deflate
Sec-WebSocket-Version: 13
Origin: http://localhost:5000
Sec-WebSocket-Extensions: permessage-deflate
Sec-WebSocket-Key: Z7OY1UwHOx/nkSz38kfPwg==
Sec-WebSocket-Protocol: chat
DNT: 1
Connection: keep-alive, Upgrade
Pragma: no-cache
Cache-Control: no-cache
Upgrade: websocket

";

        let http_header = read_http_header(&client_request.as_bytes()).unwrap();
        let web_socket_context = http_header.websocket_context.unwrap();
        assert_eq!(
            "Z7OY1UwHOx/nkSz38kfPwg==",
            web_socket_context.sec_websocket_key
        );
        assert_eq!(
            "chat",
            web_socket_context
                .sec_websocket_protocol_list
                .get(0)
                .unwrap()
                .as_str()
        );
        let mut web_socket = WebSocketServer::new_server();

        let mut ws_buffer: [u8; 3000] = [0; 3000];
        let size = web_socket
            .server_accept(&web_socket_context.sec_websocket_key, None, &mut ws_buffer)
            .unwrap();
        let response = std::str::from_utf8(&ws_buffer[..size]).unwrap();
        let client_response_expected = "HTTP/1.1 101 Switching Protocols\r\nConnection: Upgrade\r\nUpgrade: websocket\r\nSec-WebSocket-Accept: ptPnPeDOTo6khJlzmLhOZSh2tAY=\r\n\r\n";
        assert_eq!(client_response_expected, response);
    }

    #[test]
    fn server_write_frame() {
        let mut buffer: [u8; 1000] = [0; 1000];
        let mut ws_server = WebSocketServer::new_server();
        let len = ws_server
            .write_frame(
                "hello".as_bytes(),
                &mut buffer,
                WebSocketOpCode::TextFrame,
                true,
            )
            .unwrap();
        let expected = [129, 5, 104, 101, 108, 108, 111];
        assert_eq!(&expected, &buffer[..len]);
    }

    #[test]
    fn server_accept_should_write_sub_protocol() {
        let mut buffer: [u8; 1000] = [0; 1000];
        let mut ws_server = WebSocketServer::new_server();
        let ws_key = WebSocketKey::from("Z7OY1UwHOx/nkSz38kfPwg==");
        let sub_protocol = WebSocketSubProtocol::from("chat");
        let size = ws_server
            .server_accept(&ws_key, Some(&sub_protocol), &mut buffer)
            .unwrap();
        let response = std::str::from_utf8(&buffer[..size]).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);
    }

    #[test]
    fn closing_handshake() {
        let mut buffer1: [u8; 500] = [0; 500];
        let mut buffer2: [u8; 500] = [0; 500];

        let mut rng = rand::thread_rng();

        let mut ws_client = WebSocket::new_client(&mut rng);
        ws_client.state = WebSocketState::Open;

        let mut ws_server = WebSocketServer::new_server();
        ws_server.state = WebSocketState::Open;

        // client sends a close (initiates the close handshake)
        ws_client
            .close(WebSocketCloseStatusCode::NormalClosure, None, &mut buffer1)
            .unwrap();

        // check that the client receives the close message
        let ws_result = ws_server.read(&buffer1, &mut buffer2).unwrap();
        assert_eq!(
            WebSocketReceiveMessageType::CloseMustReply,
            ws_result.message_type
        );

        // server MUST respond to complete the handshake
        ws_server
            .write(
                WebSocketSendMessageType::CloseReply,
                true,
                &buffer2[..ws_result.len_to],
                &mut buffer1,
            )
            .unwrap();
        assert_eq!(WebSocketState::Closed, ws_server.state);

        // check that the client receives the close message from the server
        let ws_result = ws_client.read(&buffer1, &mut buffer2).unwrap();
        assert_eq!(WebSocketState::Closed, ws_client.state);

        assert_eq!(
            WebSocketReceiveMessageType::CloseCompleted,
            ws_result.message_type
        );
    }

    #[test]
    fn send_message_from_client_to_server() {
        let mut buffer1: [u8; 1000] = [0; 1000];
        let mut buffer2: [u8; 1000] = [0; 1000];

        // how to create a client
        let mut ws_client = WebSocket::new_client(rand::thread_rng());

        ws_client.state = WebSocketState::Open;
        let mut ws_server = WebSocketServer::new_server();
        ws_server.state = WebSocketState::Open;

        // client sends a Text message
        let hello = "hello";
        let num_bytes = ws_client
            .write(
                WebSocketSendMessageType::Text,
                true,
                &hello.as_bytes(),
                &mut buffer1,
            )
            .unwrap();

        // check that the Server receives the Text message
        let ws_result = ws_server.read(&buffer1[..num_bytes], &mut buffer2).unwrap();
        assert_eq!(WebSocketReceiveMessageType::Text, ws_result.message_type);
        let received = std::str::from_utf8(&buffer2[..ws_result.len_to]).unwrap();
        assert_eq!(hello, received);
    }

    #[test]
    fn send_message_from_server_to_client() {
        let mut buffer1: [u8; 1000] = [0; 1000];
        let mut buffer2: [u8; 1000] = [0; 1000];

        let mut ws_client = WebSocket::new_client(rand::thread_rng());
        ws_client.state = WebSocketState::Open;
        let mut ws_server = WebSocketServer::new_server();
        ws_server.state = WebSocketState::Open;

        // server sends a Text message
        let hello = "hello";
        let num_bytes = ws_server
            .write(
                WebSocketSendMessageType::Text,
                true,
                &hello.as_bytes(),
                &mut buffer1,
            )
            .unwrap();

        // check that the client receives the Text message
        let ws_result = ws_client.read(&buffer1[..num_bytes], &mut buffer2).unwrap();
        assert_eq!(WebSocketReceiveMessageType::Text, ws_result.message_type);
        let received = std::str::from_utf8(&buffer2[..ws_result.len_to]).unwrap();
        assert_eq!(hello, received);
    }

    #[test]
    fn receive_buffer_too_small() {
        let mut buffer1: [u8; 1000] = [0; 1000];
        let mut buffer2: [u8; 1000] = [0; 1000];

        let mut ws_client = WebSocket::new_client(rand::thread_rng());
        ws_client.state = WebSocketState::Open;
        let mut ws_server = WebSocketServer::new_server();
        ws_server.state = WebSocketState::Open;

        let hello = "hello";
        ws_server
            .write(
                WebSocketSendMessageType::Text,
                true,
                &hello.as_bytes(),
                &mut buffer1,
            )
            .unwrap();

        match ws_client.read(&buffer1[..1], &mut buffer2) {
            Err(Error::ReadFrameIncomplete) => {
                // test passes
            }
            _ => {
                assert_eq!(true, false);
            }
        }
    }

    #[test]
    fn receive_large_frame_with_small_receive_buffer() {
        let mut buffer1: [u8; 1000] = [0; 1000];
        let mut buffer2: [u8; 1000] = [0; 1000];

        let mut ws_client = WebSocket::new_client(rand::thread_rng());
        ws_client.state = WebSocketState::Open;
        let mut ws_server = WebSocketServer::new_server();
        ws_server.state = WebSocketState::Open;

        let hello = "hello";
        ws_server
            .write(
                WebSocketSendMessageType::Text,
                true,
                &hello.as_bytes(),
                &mut buffer1,
            )
            .unwrap();

        let ws_result = ws_client.read(&buffer1[..2], &mut buffer2).unwrap();
        assert_eq!(0, ws_result.len_to);
        assert_eq!(false, ws_result.end_of_message);
        let ws_result = ws_client.read(&buffer1[2..3], &mut buffer2).unwrap();
        assert_eq!(1, ws_result.len_to);
        assert_eq!(
            "h",
            std::str::from_utf8(&buffer2[..ws_result.len_to]).unwrap()
        );
        assert_eq!(false, ws_result.end_of_message);
        let ws_result = ws_client.read(&buffer1[3..], &mut buffer2).unwrap();
        assert_eq!(4, ws_result.len_to);
        assert_eq!(
            "ello",
            std::str::from_utf8(&buffer2[..ws_result.len_to]).unwrap()
        );
        assert_eq!(true, ws_result.end_of_message);
    }

    #[test]
    fn receive_large_frame_with_small_send_buffer() {
        let mut buffer1: [u8; 1000] = [0; 1000];
        let mut buffer2: [u8; 1000] = [0; 1000];

        let mut ws_client = WebSocket::new_client(rand::thread_rng());
        ws_client.state = WebSocketState::Open;
        let mut ws_server = WebSocketServer::new_server();
        ws_server.state = WebSocketState::Open;

        let hello = "hello";
        ws_server
            .write(
                WebSocketSendMessageType::Text,
                true,
                &hello.as_bytes(),
                &mut buffer1,
            )
            .unwrap();

        let ws_result = ws_client.read(&buffer1, &mut buffer2[..1]).unwrap();
        assert_eq!(1, ws_result.len_to);
        assert_eq!(
            "h",
            std::str::from_utf8(&buffer2[..ws_result.len_to]).unwrap()
        );
        assert_eq!(false, ws_result.end_of_message);
        let ws_result = ws_client
            .read(&buffer1[ws_result.len_from..], &mut buffer2[..4])
            .unwrap();
        assert_eq!(4, ws_result.len_to);
        assert_eq!(
            "ello",
            std::str::from_utf8(&buffer2[..ws_result.len_to]).unwrap()
        );
        assert_eq!(true, ws_result.end_of_message);
    }

    #[test]
    fn send_multi_frame_message() {
        let mut buffer1: [u8; 1000] = [0; 1000];
        let mut buffer2: [u8; 1000] = [0; 1000];
        // let mut rng = rand::thread_rng();

        let mut ws_client = WebSocket::new_client(rand::thread_rng());
        ws_client.state = WebSocketState::Open;
        let mut ws_server = WebSocketServer::new_server();
        ws_server.state = WebSocketState::Open;

        // client sends a fragmented Text message
        let hello = "Hello, ";
        let num_bytes_hello = ws_server
            .write(
                WebSocketSendMessageType::Text,
                false,
                &hello.as_bytes(),
                &mut buffer1,
            )
            .unwrap();

        // client sends the remaining Text message
        let world = "World!";
        let num_bytes_world = ws_server
            .write(
                WebSocketSendMessageType::Text,
                true,
                &world.as_bytes(),
                &mut buffer1[num_bytes_hello..],
            )
            .unwrap();

        // check that the Server receives the entire Text message
        let ws_result1 = ws_client
            .read(&buffer1[..num_bytes_hello], &mut buffer2)
            .unwrap();
        assert_eq!(WebSocketReceiveMessageType::Text, ws_result1.message_type);
        assert_eq!(false, ws_result1.end_of_message);
        let ws_result2 = ws_client
            .read(
                &buffer1[num_bytes_hello..num_bytes_hello + num_bytes_world],
                &mut buffer2[ws_result1.len_to..],
            )
            .unwrap();
        assert_eq!(WebSocketReceiveMessageType::Text, ws_result2.message_type);
        assert_eq!(true, ws_result2.end_of_message);

        let received =
            std::str::from_utf8(&buffer2[..ws_result1.len_to + ws_result2.len_to]).unwrap();
        assert_eq!("Hello, World!", received);
    }
}