-
Notifications
You must be signed in to change notification settings - Fork 204
/
Copy pathuws_client.c
2288 lines (2056 loc) · 129 KB
/
uws_client.c
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
// Copyright (c) Microsoft. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
#include <stdlib.h>
#include <stdint.h>
#include <limits.h>
#include <ctype.h>
#include <limits.h>
#include "azure_c_shared_utility/gballoc.h"
#include "azure_c_shared_utility/uws_client.h"
#include "azure_c_shared_utility/optimize_size.h"
#include "azure_c_shared_utility/xlogging.h"
#include "azure_c_shared_utility/xio.h"
#include "azure_c_shared_utility/singlylinkedlist.h"
#include "azure_c_shared_utility/socketio.h"
#include "azure_c_shared_utility/platform.h"
#include "azure_c_shared_utility/tlsio.h"
#include "azure_c_shared_utility/crt_abstractions.h"
#include "azure_c_shared_utility/buffer_.h"
#include "azure_c_shared_utility/uws_frame_encoder.h"
#include "azure_c_shared_utility/crt_abstractions.h"
#include "azure_c_shared_utility/utf8_checker.h"
#include "azure_c_shared_utility/random.h"
#include "azure_c_shared_utility/azure_base64.h"
#include "azure_c_shared_utility/optionhandler.h"
#include "azure_c_shared_utility/map.h"
#include "azure_c_shared_utility/shared_util_options.h"
#include "azure_c_shared_utility/safe_math.h"
static const char* UWS_CLIENT_OPTIONS = "uWSClientOptions";
static const char* HTTP_HEADER_KEY_VALUE_SEPARATOR = ": ";
static const size_t HTTP_HEADER_KEY_VALUE_SEPARATOR_LENGTH = 2;
static const char* HTTP_HEADER_TERMINATOR = "\r\n";
static const size_t HTTP_HEADER_TERMINATOR_LENGTH = 2;
/* Requirements not needed as they are optional:
Codes_SRS_UWS_CLIENT_01_254: [ If an endpoint receives a Ping frame and has not yet sent Pong frame(s) in response to previous Ping frame(s), the endpoint MAY elect to send a Pong frame for only the most recently processed Ping frame. ]
Codes_SRS_UWS_CLIENT_01_255: [ A Pong frame MAY be sent unsolicited. ]
Codes_SRS_UWS_CLIENT_01_256: [ A response to an unsolicited Pong frame is not expected. ]
*/
/* Requirements satisfied by the underlying TLS/socket stack
Codes_SRS_UWS_CLIENT_01_362: [ To achieve reasonable levels of protection, clients should use only Strong TLS algorithms. ]
Codes_SRS_UWS_CLIENT_01_289: [ An endpoint SHOULD use a method that cleanly closes the TCP connection, as well as the TLS session, if applicable, discarding any trailing bytes that may have been received. ]
Codes_SRS_UWS_CLIENT_01_078: [ Otherwise, all further communication on this channel MUST run through the encrypted tunnel [RFC5246]. ]
Codes_SRS_UWS_CLIENT_01_141: [ masking is done whether or not the WebSocket Protocol is running over TLS. ]
*/
/* Requirements satisfied by the way the APIs are designed:
Codes_SRS_UWS_CLIENT_01_211: [One implication of this is that in absence of extensions, senders and receivers must not depend on the presence of specific frame boundaries.]
*/
typedef enum UWS_STATE_TAG
{
UWS_STATE_CLOSED,
UWS_STATE_OPENING_UNDERLYING_IO,
UWS_STATE_WAITING_FOR_UPGRADE_RESPONSE,
UWS_STATE_OPEN,
UWS_STATE_CLOSING_WAITING_FOR_CLOSE,
UWS_STATE_CLOSING_SENDING_CLOSE,
UWS_STATE_CLOSING_UNDERLYING_IO,
UWS_STATE_ERROR
} UWS_STATE;
typedef struct WS_INSTANCE_PROTOCOL_TAG
{
char* protocol;
} WS_INSTANCE_PROTOCOL;
typedef struct WS_PENDING_SEND_TAG
{
ON_WS_SEND_FRAME_COMPLETE on_ws_send_frame_complete;
void* context;
UWS_CLIENT_HANDLE uws_client;
} WS_PENDING_SEND;
typedef struct UWS_CLIENT_INSTANCE_TAG
{
SINGLYLINKEDLIST_HANDLE pending_sends;
XIO_HANDLE underlying_io;
char* hostname;
char* resource_name;
WS_INSTANCE_PROTOCOL* protocols;
size_t protocol_count;
int port;
MAP_HANDLE request_headers;
UWS_STATE uws_state;
ON_WS_OPEN_COMPLETE on_ws_open_complete;
void* on_ws_open_complete_context;
ON_WS_FRAME_RECEIVED on_ws_frame_received;
void* on_ws_frame_received_context;
ON_WS_PEER_CLOSED on_ws_peer_closed;
void* on_ws_peer_closed_context;
ON_WS_ERROR on_ws_error;
void* on_ws_error_context;
ON_WS_CLOSE_COMPLETE on_ws_close_complete;
void* on_ws_close_complete_context;
unsigned char* stream_buffer;
size_t stream_buffer_size;
size_t stream_buffer_count;
unsigned char* fragment_buffer;
size_t fragment_buffer_count;
unsigned char fragmented_frame_type;
} UWS_CLIENT_INSTANCE;
/* Codes_SRS_UWS_CLIENT_01_360: [ Connection confidentiality and integrity is provided by running the WebSocket Protocol over TLS (wss URIs). ]*/
/* Codes_SRS_UWS_CLIENT_01_361: [ WebSocket implementations MUST support TLS and SHOULD employ it when communicating with their peers. ]*/
/* Codes_SRS_UWS_CLIENT_01_063: [ A client will need to supply a /host/, /port/, /resource name/, and a /secure/ flag, which are the components of a WebSocket URI as discussed in Section 3, along with a list of /protocols/ and /extensions/ to be used. ]*/
UWS_CLIENT_HANDLE uws_client_create(const char* hostname, unsigned int port, const char* resource_name, bool use_ssl, const WS_PROTOCOL* protocols, size_t protocol_count)
{
UWS_CLIENT_HANDLE result;
/* Codes_SRS_UWS_CLIENT_01_002: [ If any of the arguments hostname and resource_name is NULL then uws_client_create shall return NULL. ]*/
if ((hostname == NULL) ||
(resource_name == NULL) ||
/* Codes_SRS_UWS_CLIENT_01_411: [ If protocol_count is non zero and protocols is NULL then uws_client_create shall fail and return NULL. ]*/
((protocols == NULL) && (protocol_count > 0)))
{
LogError("Invalid arguments: hostname = %p, resource_name = %p, protocols = %p, protocol_count = %lu", hostname, resource_name, protocols, (unsigned long)protocol_count);
result = NULL;
}
else
{
/* Codes_SRS_UWS_CLIENT_01_412: [ If the protocol member of any of the items in the protocols argument is NULL, then uws_client_create shall fail and return NULL. ]*/
size_t i;
for (i = 0; i < protocol_count; i++)
{
if (protocols[i].protocol == NULL)
{
break;
}
}
if (i < protocol_count)
{
LogError("Protocol index %lu has NULL name", (unsigned long)i);
result = NULL;
}
else
{
/* Codes_SRS_UWS_CLIENT_01_001: [uws_client_create shall create an instance of uws and return a non-NULL handle to it.]*/
result = (UWS_CLIENT_HANDLE)malloc(sizeof(UWS_CLIENT_INSTANCE));
if (result == NULL)
{
/* Codes_SRS_UWS_CLIENT_01_003: [ If allocating memory for the new uws instance fails then uws_client_create shall return NULL. ]*/
LogError("Could not allocate uWS instance");
}
else
{
(void)memset(result, 0, sizeof(UWS_CLIENT_INSTANCE));
/* Codes_SRS_UWS_CLIENT_01_004: [ The argument hostname shall be copied for later use. ]*/
if (mallocAndStrcpy_s(&result->hostname, hostname) != 0)
{
/* Codes_SRS_UWS_CLIENT_01_392: [ If allocating memory for the copy of the hostname argument fails, then uws_client_create shall return NULL. ]*/
LogError("Could not copy hostname.");
free(result);
result = NULL;
}
else
{
/* Codes_SRS_UWS_CLIENT_01_404: [ The argument resource_name shall be copied for later use. ]*/
if (mallocAndStrcpy_s(&result->resource_name, resource_name) != 0)
{
/* Codes_SRS_UWS_CLIENT_01_405: [ If allocating memory for the copy of the resource argument fails, then uws_client_create shall return NULL. ]*/
LogError("Could not copy resource.");
free(result->hostname);
free(result);
result = NULL;
}
else if ((result->request_headers = Map_Create(NULL)) == NULL)
{
LogError("Failed allocating MAP for request headers");
free(result->resource_name);
free(result->hostname);
free(result);
result = NULL;
}
else
{
/* Codes_SRS_UWS_CLIENT_01_017: [ uws_client_create shall create a pending send IO list that is to be used to queue send packets by calling singlylinkedlist_create. ]*/
result->pending_sends = singlylinkedlist_create();
if (result->pending_sends == NULL)
{
/* Codes_SRS_UWS_CLIENT_01_018: [ If singlylinkedlist_create fails then uws_client_create shall fail and return NULL. ]*/
LogError("Could not allocate pending send frames list");
Map_Destroy(result->request_headers);
free(result->resource_name);
free(result->hostname);
free(result);
result = NULL;
}
else
{
if (use_ssl == true)
{
TLSIO_CONFIG tlsio_config;
/* Codes_SRS_UWS_CLIENT_01_006: [ If use_ssl is true then uws_client_create shall obtain the interface used to create a tlsio instance by calling platform_get_default_tlsio. ]*/
/* Codes_SRS_UWS_CLIENT_01_076: [ If /secure/ is true, the client MUST perform a TLS handshake over the connection after opening the connection and before sending the handshake data [RFC2818]. ]*/
const IO_INTERFACE_DESCRIPTION* tlsio_interface = platform_get_default_tlsio();
if (tlsio_interface == NULL)
{
/* Codes_SRS_UWS_CLIENT_01_007: [ If obtaining the underlying IO interface fails, then uws_client_create shall fail and return NULL. ]*/
LogError("NULL TLSIO interface description");
result->underlying_io = NULL;
}
else
{
SOCKETIO_CONFIG socketio_config;
/* Codes_SRS_UWS_CLIENT_01_013: [ The create arguments for the tls IO (when use_ssl is 1) shall have: ]*/
/* Codes_SRS_UWS_CLIENT_01_014: [ - hostname set to the hostname argument passed to uws_client_create. ]*/
/* Codes_SRS_UWS_CLIENT_01_015: [ - port set to the port argument passed to uws_client_create. ]*/
socketio_config.hostname = hostname;
socketio_config.port = port;
socketio_config.accepted_socket = NULL;
tlsio_config.hostname = hostname;
tlsio_config.port = port;
tlsio_config.underlying_io_interface = socketio_get_interface_description();
tlsio_config.underlying_io_parameters = &socketio_config;
result->underlying_io = xio_create(tlsio_interface, &tlsio_config);
if (result->underlying_io == NULL)
{
LogError("Cannot create underlying TLS IO.");
}
else
{
// Set the underlying socket to turn on renegotiation
bool set_renegotiation = true;
xio_setoption(result->underlying_io, OPTION_SET_TLS_RENEGOTIATION, &set_renegotiation);
}
}
}
else
{
SOCKETIO_CONFIG socketio_config;
/* Codes_SRS_UWS_CLIENT_01_005: [ If use_ssl is false then uws_client_create shall obtain the interface used to create a socketio instance by calling socketio_get_interface_description. ]*/
const IO_INTERFACE_DESCRIPTION* socketio_interface = socketio_get_interface_description();
if (socketio_interface == NULL)
{
/* Codes_SRS_UWS_CLIENT_01_007: [ If obtaining the underlying IO interface fails, then uws_client_create shall fail and return NULL. ]*/
LogError("NULL socketio interface description");
result->underlying_io = NULL;
}
else
{
/* Codes_SRS_UWS_CLIENT_01_010: [ The create arguments for the socket IO (when use_ssl is 0) shall have: ]*/
/* Codes_SRS_UWS_CLIENT_01_011: [ - hostname set to the hostname argument passed to uws_client_create. ]*/
/* Codes_SRS_UWS_CLIENT_01_012: [ - port set to the port argument passed to uws_client_create. ]*/
socketio_config.hostname = hostname;
socketio_config.port = port;
socketio_config.accepted_socket = NULL;
/* Codes_SRS_UWS_CLIENT_01_008: [ The obtained interface shall be used to create the IO used as underlying IO by the newly created uws instance. ]*/
/* Codes_SRS_UWS_CLIENT_01_009: [ The underlying IO shall be created by calling xio_create. ]*/
result->underlying_io = xio_create(socketio_interface, &socketio_config);
if (result->underlying_io == NULL)
{
LogError("Cannot create underlying socket IO.");
}
}
}
if (result->underlying_io == NULL)
{
/* Codes_SRS_UWS_CLIENT_01_016: [ If xio_create fails, then uws_client_create shall fail and return NULL. ]*/
singlylinkedlist_destroy(result->pending_sends);
Map_Destroy(result->request_headers);
free(result->resource_name);
free(result->hostname);
free(result);
result = NULL;
}
else
{
result->uws_state = UWS_STATE_CLOSED;
/* Codes_SRS_UWS_CLIENT_01_403: [ The argument port shall be copied for later use. ]*/
result->port = port;
result->fragmented_frame_type = WS_FRAME_TYPE_UNKNOWN;
result->protocol_count = protocol_count;
/* Codes_SRS_UWS_CLIENT_01_410: [ The protocols argument shall be allowed to be NULL, in which case no protocol is to be specified by the client in the upgrade request. ]*/
if (protocols == NULL)
{
result->protocols = NULL;
}
else
{
size_t malloc_size = safe_multiply_size_t(sizeof(WS_INSTANCE_PROTOCOL), protocol_count);
if (malloc_size == SIZE_MAX ||
(result->protocols = (WS_INSTANCE_PROTOCOL*)malloc(malloc_size)) == NULL)
{
/* Codes_SRS_UWS_CLIENT_01_414: [ If allocating memory for the copied protocol information fails then uws_client_create shall fail and return NULL. ]*/
LogError("Cannot allocate memory for the protocols array. size=%zu", malloc_size);
xio_destroy(result->underlying_io);
singlylinkedlist_destroy(result->pending_sends);
Map_Destroy(result->request_headers);
free(result->resource_name);
free(result->hostname);
free(result);
result = NULL;
}
else
{
/* Codes_SRS_UWS_CLIENT_01_413: [ The protocol information indicated by protocols and protocol_count shall be copied for later use (for constructing the upgrade request). ]*/
for (i = 0; i < protocol_count; i++)
{
if (mallocAndStrcpy_s(&result->protocols[i].protocol, protocols[i].protocol) != 0)
{
/* Codes_SRS_UWS_CLIENT_01_414: [ If allocating memory for the copied protocol information fails then uws_client_create shall fail and return NULL. ]*/
LogError("Cannot allocate memory for the protocol index %u.", (unsigned int)i);
break;
}
}
if (i < protocol_count)
{
size_t j;
for (j = 0; j < i; j++)
{
free(result->protocols[j].protocol);
}
free(result->protocols);
xio_destroy(result->underlying_io);
singlylinkedlist_destroy(result->pending_sends);
Map_Destroy(result->request_headers);
free(result->resource_name);
free(result->hostname);
free(result);
result = NULL;
}
else
{
result->protocol_count = protocol_count;
}
}
}
}
}
}
}
}
}
}
return result;
}
UWS_CLIENT_HANDLE uws_client_create_with_io(const IO_INTERFACE_DESCRIPTION* io_interface, void* io_create_parameters, const char* hostname, unsigned int port, const char* resource_name, const WS_PROTOCOL* protocols, size_t protocol_count)
{
UWS_CLIENT_HANDLE result;
/* Codes_SRS_UWS_CLIENT_01_516: [ If any of the arguments io_interface, hostname and resource_name is NULL then uws_client_create_with_io shall return NULL. ]*/
if ((hostname == NULL) ||
(io_interface == NULL) ||
(resource_name == NULL) ||
/* Codes_SRS_UWS_CLIENT_01_525: [ If protocol_count is non zero and protocols is NULL then uws_client_create_with_io shall fail and return NULL. ]*/
((protocols == NULL) && (protocol_count > 0)))
{
LogError("Invalid arguments: io_interface = %p, resource_name = %p, protocols = %p, protocol_count = %lu", io_interface, resource_name, protocols, (unsigned long)protocol_count);
result = NULL;
}
else
{
size_t i;
for (i = 0; i < protocol_count; i++)
{
if (protocols[i].protocol == NULL)
{
break;
}
}
if (i < protocol_count)
{
/* Codes_SRS_UWS_CLIENT_01_526: [ If the protocol member of any of the items in the protocols argument is NULL, then uws_client_create_with_io shall fail and return NULL. ]*/
LogError("Protocol index %lu has NULL name", (unsigned long)i);
result = NULL;
}
else
{
/* Codes_SRS_UWS_CLIENT_01_515: [ uws_client_create_with_io shall create an instance of uws and return a non-NULL handle to it. ]*/
result = (UWS_CLIENT_HANDLE)malloc(sizeof(UWS_CLIENT_INSTANCE));
if (result == NULL)
{
/* Codes_SRS_UWS_CLIENT_01_517: [ If allocating memory for the new uws instance fails then uws_client_create_with_io shall return NULL. ]*/
LogError("Could not allocate uWS instance");
}
else
{
memset(result, 0, sizeof(UWS_CLIENT_INSTANCE));
/* Codes_SRS_UWS_CLIENT_01_518: [ The argument hostname shall be copied for later use. ]*/
if (mallocAndStrcpy_s(&result->hostname, hostname) != 0)
{
/* Codes_SRS_UWS_CLIENT_01_519: [ If allocating memory for the copy of the hostname argument fails, then uws_client_create shall return NULL. ]*/
LogError("Could not copy hostname.");
free(result);
result = NULL;
}
else
{
/* Codes_SRS_UWS_CLIENT_01_523: [ The argument resource_name shall be copied for later use. ]*/
if (mallocAndStrcpy_s(&result->resource_name, resource_name) != 0)
{
/* Codes_SRS_UWS_CLIENT_01_529: [ If allocating memory for the copy of the resource_name argument fails, then uws_client_create_with_io shall return NULL. ]*/
LogError("Could not copy resource.");
free(result->hostname);
free(result);
result = NULL;
}
else if ((result->request_headers = Map_Create(NULL)) == NULL)
{
LogError("Failed allocating MAP for request headers");
free(result->resource_name);
free(result->hostname);
free(result);
result = NULL;
}
else
{
/* Codes_SRS_UWS_CLIENT_01_530: [ uws_client_create_with_io shall create a pending send IO list that is to be used to queue send packets by calling singlylinkedlist_create. ]*/
result->pending_sends = singlylinkedlist_create();
if (result->pending_sends == NULL)
{
/* Codes_SRS_UWS_CLIENT_01_531: [ If singlylinkedlist_create fails then uws_client_create_with_io shall fail and return NULL. ]*/
LogError("Could not allocate pending send frames list");
Map_Destroy(result->request_headers);
free(result->resource_name);
free(result->hostname);
free(result);
result = NULL;
}
else
{
/* Codes_SRS_UWS_CLIENT_01_521: [ The underlying IO shall be created by calling xio_create, while passing as arguments the io_interface and io_create_parameters argument values. ]*/
result->underlying_io = xio_create(io_interface, io_create_parameters);
if (result->underlying_io == NULL)
{
/* Codes_SRS_UWS_CLIENT_01_522: [ If xio_create fails, then uws_client_create_with_io shall fail and return NULL. ]*/
LogError("Cannot create underlying IO.");
singlylinkedlist_destroy(result->pending_sends);
Map_Destroy(result->request_headers);
free(result->resource_name);
free(result->hostname);
free(result);
result = NULL;
}
else
{
// Set the underlying socket to turn on renegotiation
bool set_renegotiation = true;
(void)xio_setoption(result->underlying_io, OPTION_SET_TLS_RENEGOTIATION, &set_renegotiation);
result->uws_state = UWS_STATE_CLOSED;
/* Codes_SRS_UWS_CLIENT_01_520: [ The argument port shall be copied for later use. ]*/
result->port = port;
result->fragmented_frame_type = WS_FRAME_TYPE_UNKNOWN;
result->protocol_count = protocol_count;
/* Codes_SRS_UWS_CLIENT_01_524: [ The protocols argument shall be allowed to be NULL, in which case no protocol is to be specified by the client in the upgrade request. ]*/
if (protocols == NULL)
{
result->protocols = NULL;
}
else
{
size_t malloc_size = safe_multiply_size_t(sizeof(WS_INSTANCE_PROTOCOL), protocol_count);
if (malloc_size == SIZE_MAX ||
(result->protocols = (WS_INSTANCE_PROTOCOL*)malloc(malloc_size)) == NULL)
{
/* Codes_SRS_UWS_CLIENT_01_414: [ If allocating memory for the copied protocol information fails then uws_client_create shall fail and return NULL. ]*/
LogError("Cannot allocate memory for the protocols array. size=%zu", malloc_size);
xio_destroy(result->underlying_io);
singlylinkedlist_destroy(result->pending_sends);
Map_Destroy(result->request_headers);
free(result->resource_name);
free(result->hostname);
free(result);
result = NULL;
}
else
{
/* Codes_SRS_UWS_CLIENT_01_527: [ The protocol information indicated by protocols and protocol_count shall be copied for later use (for constructing the upgrade request). ]*/
for (i = 0; i < protocol_count; i++)
{
if (mallocAndStrcpy_s(&result->protocols[i].protocol, protocols[i].protocol) != 0)
{
/* Codes_SRS_UWS_CLIENT_01_528: [ If allocating memory for the copied protocol information fails then uws_client_create_with_io shall fail and return NULL. ]*/
LogError("Cannot allocate memory for the protocol index %u.", (unsigned int)i);
break;
}
}
if (i < protocol_count)
{
size_t j;
for (j = 0; j < i; j++)
{
free(result->protocols[j].protocol);
}
free(result->protocols);
xio_destroy(result->underlying_io);
singlylinkedlist_destroy(result->pending_sends);
Map_Destroy(result->request_headers);
free(result->resource_name);
free(result->hostname);
free(result);
result = NULL;
}
else
{
result->protocol_count = protocol_count;
}
}
}
}
}
}
}
}
}
}
return result;
}
void uws_client_destroy(UWS_CLIENT_HANDLE uws_client)
{
/* Codes_SRS_UWS_CLIENT_01_020: [ If uws_client is NULL, uws_client_destroy shall do nothing. ]*/
if (uws_client == NULL)
{
LogError("NULL uws handle");
}
else
{
free(uws_client->stream_buffer);
free(uws_client->fragment_buffer);
uws_client->stream_buffer = NULL;
uws_client->fragment_buffer = NULL;
/* Codes_SRS_UWS_CLIENT_01_021: [ uws_client_destroy shall perform a close action if the uws instance has already been open. ]*/
switch (uws_client->uws_state)
{
default:
break;
case UWS_STATE_OPEN:
case UWS_STATE_ERROR:
uws_client_close_async(uws_client, NULL, NULL);
break;
}
if (uws_client->protocol_count > 0)
{
size_t i;
/* Codes_SRS_UWS_CLIENT_01_437: [ uws_client_destroy shall free the protocols array allocated in uws_client_create. ]*/
for (i = 0; i < uws_client->protocol_count; i++)
{
free(uws_client->protocols[i].protocol);
uws_client->protocols[i].protocol = NULL;
}
free(uws_client->protocols);
uws_client->protocols = NULL;
}
/* Codes_SRS_UWS_CLIENT_01_019: [ uws_client_destroy shall free all resources associated with the uws instance. ]*/
/* Codes_SRS_UWS_CLIENT_01_023: [ uws_client_destroy shall ensure the underlying IO created in uws_client_open_async is destroyed by calling xio_destroy. ]*/
if (uws_client->underlying_io != NULL)
{
xio_destroy(uws_client->underlying_io);
uws_client->underlying_io = NULL;
}
/* Codes_SRS_UWS_CLIENT_01_024: [ uws_client_destroy shall free the list used to track the pending sends by calling singlylinkedlist_destroy. ]*/
singlylinkedlist_destroy(uws_client->pending_sends);
free(uws_client->resource_name);
free(uws_client->hostname);
Map_Destroy(uws_client->request_headers);
free(uws_client);
}
}
static void indicate_ws_open_complete_error(UWS_CLIENT_INSTANCE* uws_client, WS_OPEN_RESULT ws_open_result)
{
/* Codes_SRS_UWS_CLIENT_01_409: [ After any error is indicated by on_ws_open_complete, a subsequent uws_client_open_async shall be possible. ]*/
uws_client->uws_state = UWS_STATE_CLOSED;
uws_client->on_ws_open_complete(uws_client->on_ws_open_complete_context, ws_open_result);
}
static void indicate_ws_open_complete_error_and_close(UWS_CLIENT_INSTANCE* uws_client, WS_OPEN_RESULT ws_open_result)
{
(void)xio_close(uws_client->underlying_io, NULL, NULL);
indicate_ws_open_complete_error(uws_client, ws_open_result);
}
static void indicate_ws_error(UWS_CLIENT_INSTANCE* uws_client, WS_ERROR error_code)
{
uws_client->uws_state = UWS_STATE_ERROR;
uws_client->on_ws_error(uws_client->on_ws_error_context, error_code);
}
static void indicate_ws_close_complete(UWS_CLIENT_INSTANCE* uws_client)
{
uws_client->uws_state = UWS_STATE_CLOSED;
/* Codes_SRS_UWS_CLIENT_01_496: [ If the close was initiated by the peer no on_ws_close_complete shall be called. ]*/
if (uws_client->on_ws_close_complete != NULL)
{
/* Codes_SRS_UWS_CLIENT_01_491: [ When calling on_ws_close_complete callback, the on_ws_close_complete_context argument shall be passed to it. ]*/
uws_client->on_ws_close_complete(uws_client->on_ws_close_complete_context);
}
}
// This callback usage needs to be either verified and commented or integrated into
// the state machine.
static void unchecked_on_send_complete(void* context, IO_SEND_RESULT send_result)
{
(void)context;
(void)send_result;
}
static int send_close_frame(UWS_CLIENT_INSTANCE* uws_client, unsigned int close_error_code)
{
unsigned char* close_frame;
unsigned char close_frame_payload[2];
size_t close_frame_length;
int result;
BUFFER_HANDLE close_frame_buffer;
close_frame_payload[0] = (unsigned char)(close_error_code >> 8);
close_frame_payload[1] = (unsigned char)(close_error_code & 0xFF);
/* Codes_SRS_UWS_CLIENT_01_140: [ To avoid confusing network intermediaries (such as intercepting proxies) and for security reasons that are further discussed in Section 10.3, a client MUST mask all frames that it sends to the server (see Section 5.3 for further details). ]*/
close_frame_buffer = uws_frame_encoder_encode(WS_CLOSE_FRAME, close_frame_payload, sizeof(close_frame_payload), true, true, 0);
if (close_frame_buffer == NULL)
{
LogError("Encoding of CLOSE failed.");
result = MU_FAILURE;
}
else
{
close_frame = BUFFER_u_char(close_frame_buffer);
close_frame_length = BUFFER_length(close_frame_buffer);
/* Codes_SRS_UWS_CLIENT_01_471: [ The callback on_underlying_io_close_sent shall be passed as argument to xio_send. ]*/
if (uws_client == NULL ||
xio_send(uws_client->underlying_io, close_frame, close_frame_length, unchecked_on_send_complete, NULL) != 0)
{
LogError("Sending CLOSE frame failed.");
result = MU_FAILURE;
}
else
{
result = 0;
}
BUFFER_delete(close_frame_buffer);
}
return result;
}
static void indicate_ws_error_and_close(UWS_CLIENT_INSTANCE* uws_client, WS_ERROR error_code, unsigned int close_error_code)
{
uws_client->uws_state = UWS_STATE_ERROR;
(void)send_close_frame(uws_client, close_error_code);
uws_client->on_ws_error(uws_client->on_ws_error_context, error_code);
}
static char* get_request_headers(MAP_HANDLE headers)
{
char* result;
const char* const* keys;
const char* const* values;
size_t count;
if (Map_GetInternals(headers, &keys, &values, &count) != MAP_OK)
{
LogError("Failed getting the request headers");
result = NULL;
}
else
{
size_t length = 0;
size_t i;
for (i = 0; i < count; i++)
{
// 4 = 2 (": ") + 2 ("\r\n")
length += strlen(keys[i]) + strlen(values[i]) + 4;
}
size_t malloc_size = safe_multiply_size_t(safe_add_size_t(length, 1), sizeof(char));
if (malloc_size == SIZE_MAX ||
(result = (char*)malloc(malloc_size)) == NULL)
{
LogError("Failed allocating string for request headers, size=%zu", malloc_size);
result = NULL;
}
else
{
size_t position = 0;
for (i = 0; i < count; i++)
{
size_t key_length = strlen(keys[i]);
size_t value_length = strlen(values[i]);
(void)memcpy(result + position, keys[i], key_length);
position += key_length;
(void)memcpy(result + position, HTTP_HEADER_KEY_VALUE_SEPARATOR, HTTP_HEADER_KEY_VALUE_SEPARATOR_LENGTH);
position += HTTP_HEADER_KEY_VALUE_SEPARATOR_LENGTH;
(void)memcpy(result + position, values[i], value_length);
position += value_length;
(void)memcpy(result + position, HTTP_HEADER_TERMINATOR, HTTP_HEADER_TERMINATOR_LENGTH);
position += HTTP_HEADER_TERMINATOR_LENGTH;
}
result[position] = '\0';
}
}
return result;
}
static void on_underlying_io_open_complete(void* context, IO_OPEN_RESULT open_result)
{
UWS_CLIENT_HANDLE uws_client = (UWS_CLIENT_HANDLE)context;
/* Codes_SRS_UWS_CLIENT_01_401: [ If on_underlying_io_open_complete is called with a NULL context, on_underlying_io_open_complete shall do nothing. ]*/
if (uws_client == NULL)
{
LogError("NULL context");
}
else
{
switch (uws_client->uws_state)
{
default:
case UWS_STATE_WAITING_FOR_UPGRADE_RESPONSE:
/* Codes_SRS_UWS_CLIENT_01_407: [ When on_underlying_io_open_complete is called when the uws instance has send the upgrade request but it is waiting for the response, an error shall be reported to the user by calling the on_ws_open_complete with WS_OPEN_ERROR_MULTIPLE_UNDERLYING_IO_OPEN_EVENTS. ]*/
LogError("underlying on_io_open_complete was called again after upgrade request was sent.");
indicate_ws_open_complete_error_and_close(uws_client, WS_OPEN_ERROR_MULTIPLE_UNDERLYING_IO_OPEN_EVENTS);
break;
case UWS_STATE_OPENING_UNDERLYING_IO:
switch (open_result)
{
default:
case IO_OPEN_ERROR:
/* Codes_SRS_UWS_CLIENT_01_369: [ When on_underlying_io_open_complete is called with IO_OPEN_ERROR while uws is OPENING (uws_client_open_async was called), uws shall report that the open failed by calling the on_ws_open_complete callback passed to uws_client_open_async with WS_OPEN_ERROR_UNDERLYING_IO_OPEN_FAILED. ]*/
indicate_ws_open_complete_error(uws_client, WS_OPEN_ERROR_UNDERLYING_IO_OPEN_FAILED);
break;
case IO_OPEN_CANCELLED:
/* Codes_SRS_UWS_CLIENT_01_402: [ When on_underlying_io_open_complete is called with IO_OPEN_CANCELLED while uws is OPENING (uws_client_open_async was called), uws shall report that the open failed by calling the on_ws_open_complete callback passed to uws_client_open_async with WS_OPEN_ERROR_UNDERLYING_IO_OPEN_CANCELLED. ]*/
indicate_ws_open_complete_error(uws_client, WS_OPEN_ERROR_UNDERLYING_IO_OPEN_CANCELLED);
break;
case IO_OPEN_OK:
{
int upgrade_request_length;
char* upgrade_request;
size_t i;
unsigned char nonce[16];
STRING_HANDLE base64_nonce;
char* request_headers = NULL;
/* Codes_SRS_UWS_CLIENT_01_089: [ The value of this header field MUST be a nonce consisting of a randomly selected 16-byte value that has been base64-encoded (see Section 4 of [RFC4648]). ]*/
/* Codes_SRS_UWS_CLIENT_01_090: [ The nonce MUST be selected randomly for each connection. ]*/
for (i = 0; i < sizeof(nonce); i++)
{
nonce[i] = (unsigned char)RANDOM_generate();
}
/* Codes_SRS_UWS_CLIENT_01_497: [ The nonce needed for the upgrade request shall be Base64 encoded with Azure_Base64_Encode_Bytes. ]*/
base64_nonce = Azure_Base64_Encode_Bytes(nonce, sizeof(nonce));
if (base64_nonce == NULL)
{
/* Codes_SRS_UWS_CLIENT_01_498: [ If Base64 encoding the nonce for the upgrade request fails, then the uws client shall report that the open failed by calling the on_ws_open_complete callback passed to uws_client_open_async with WS_OPEN_ERROR_BASE64_ENCODE_FAILED. ]*/
LogError("Cannot construct the WebSocket upgrade request");
indicate_ws_open_complete_error(uws_client, WS_OPEN_ERROR_BASE64_ENCODE_FAILED);
}
else if ((request_headers = get_request_headers(uws_client->request_headers)) == NULL)
{
LogError("Cannot construct the WebSocket request headers");
indicate_ws_open_complete_error(uws_client, WS_OPEN_ERROR_CONSTRUCTING_UPGRADE_REQUEST);
}
else
{
/* Codes_SRS_UWS_CLIENT_01_371: [ When on_underlying_io_open_complete is called with IO_OPEN_OK while uws is OPENING (uws_client_open_async was called), uws shall prepare the WebSockets upgrade request. ]*/
/* Codes_SRS_UWS_CLIENT_01_081: [ The handshake consists of an HTTP Upgrade request, along with a list of required and optional header fields. ]*/
/* Codes_SRS_UWS_CLIENT_01_082: [ The handshake MUST be a valid HTTP request as specified by [RFC2616]. ]*/
/* Codes_SRS_UWS_CLIENT_01_083: [ The method of the request MUST be GET, and the HTTP version MUST be at least 1.1. ]*/
/* Codes_SRS_UWS_CLIENT_01_084: [ The "Request-URI" part of the request MUST match the /resource name/ defined in Section 3 (a relative URI) or be an absolute http/https URI that, when parsed, has a /resource name/, /host/, and /port/ that match the corresponding ws/wss URI. ]*/
/* Codes_SRS_UWS_CLIENT_01_085: [ The request MUST contain a |Host| header field whose value contains /host/ plus optionally ":" followed by /port/ (when not using the default port). ]*/
/* Codes_SRS_UWS_CLIENT_01_086: [ The request MUST contain an |Upgrade| header field whose value MUST include the "websocket" keyword. ]*/
/* Codes_SRS_UWS_CLIENT_01_087: [ The request MUST contain a |Connection| header field whose value MUST include the "Upgrade" token. ]*/
/* Codes_SRS_UWS_CLIENT_01_088: [ The request MUST include a header field with the name |Sec-WebSocket-Key|. ]*/
/* Codes_SRS_UWS_CLIENT_01_094: [ The request MUST include a header field with the name |Sec-WebSocket-Version|. ]*/
/* Codes_SRS_UWS_CLIENT_01_095: [ The value of this header field MUST be 13. ]*/
/* Codes_SRS_UWS_CLIENT_01_096: [ The request MAY include a header field with the name |Sec-WebSocket-Protocol|. ]*/
/* Codes_SRS_UWS_CLIENT_01_100: [ The request MAY include a header field with the name |Sec-WebSocket-Extensions|. ]*/
/* Codes_SRS_UWS_CLIENT_01_101: [ The request MAY include any other header fields, for example, cookies [RFC6265] and/or authentication-related header fields such as the |Authorization| header field [RFC2616], which are processed according to documents that define them. ] */
const char upgrade_request_format[] = "GET %s HTTP/1.1\r\n"
"Host: %s:%d\r\n"
"Upgrade: websocket\r\n"
"Connection: Upgrade\r\n"
"Sec-WebSocket-Key: %s\r\n"
"Sec-WebSocket-Protocol: %s\r\n"
"Sec-WebSocket-Version: 13\r\n"
"%s"
"\r\n";
const char* base64_nonce_chars = STRING_c_str(base64_nonce);
upgrade_request_length = (int)(strlen(upgrade_request_format) + strlen(uws_client->resource_name)+strlen(uws_client->hostname) + strlen(base64_nonce_chars) + strlen(uws_client->protocols[0].protocol) + strlen(request_headers) + 5);
if (upgrade_request_length < 0)
{
/* Codes_SRS_UWS_CLIENT_01_408: [ If constructing of the WebSocket upgrade request fails, uws shall report that the open failed by calling the on_ws_open_complete callback passed to uws_client_open_async with WS_OPEN_ERROR_CONSTRUCTING_UPGRADE_REQUEST. ]*/
LogError("Cannot construct the WebSocket upgrade request");
indicate_ws_open_complete_error_and_close(uws_client, WS_OPEN_ERROR_CONSTRUCTING_UPGRADE_REQUEST);
}
else
{
size_t malloc_size = safe_add_size_t((size_t)upgrade_request_length, 1);
if (malloc_size == SIZE_MAX ||
(upgrade_request = (char*)malloc(malloc_size)) == NULL)
{
/* Codes_SRS_UWS_CLIENT_01_406: [ If not enough memory can be allocated to construct the WebSocket upgrade request, uws shall report that the open failed by calling the on_ws_open_complete callback passed to uws_client_open_async with WS_OPEN_ERROR_NOT_ENOUGH_MEMORY. ]*/
LogError("Cannot allocate memory for the WebSocket upgrade request");
indicate_ws_open_complete_error_and_close(uws_client, WS_OPEN_ERROR_NOT_ENOUGH_MEMORY);
}
else
{
upgrade_request_length = sprintf(upgrade_request, upgrade_request_format,
uws_client->resource_name,
uws_client->hostname,
uws_client->port,
base64_nonce_chars,
uws_client->protocols[0].protocol,
request_headers);
/* No need to have any send complete here, as we are monitoring the received bytes */
/* Codes_SRS_UWS_CLIENT_01_372: [ Once prepared the WebSocket upgrade request shall be sent by calling xio_send. ]*/
/* Codes_SRS_UWS_CLIENT_01_080: [ Once a connection to the server has been established (including a connection via a proxy or over a TLS-encrypted tunnel), the client MUST send an opening handshake to the server. ]*/
if (xio_send(uws_client->underlying_io, upgrade_request, upgrade_request_length, unchecked_on_send_complete, NULL) != 0)
{
/* Codes_SRS_UWS_CLIENT_01_373: [ If xio_send fails then uws shall report that the open failed by calling the on_ws_open_complete callback passed to uws_client_open_async with WS_OPEN_ERROR_CANNOT_SEND_UPGRADE_REQUEST. ]*/
LogError("Cannot send upgrade request");
indicate_ws_open_complete_error_and_close(uws_client, WS_OPEN_ERROR_CANNOT_SEND_UPGRADE_REQUEST);
}
else
{
/* Codes_SRS_UWS_CLIENT_01_102: [ Once the client's opening handshake has been sent, the client MUST wait for a response from the server before sending any further data. ]*/
uws_client->uws_state = UWS_STATE_WAITING_FOR_UPGRADE_RESPONSE;
}
free(upgrade_request);
upgrade_request = NULL;
}
}
STRING_delete(base64_nonce);
free(request_headers);
}
break;
}
}
}
}
}
static void consume_stream_buffer_bytes(UWS_CLIENT_INSTANCE* uws_client, size_t consumed_bytes)
{
if (consumed_bytes < uws_client->stream_buffer_count)
{
(void)memmove(uws_client->stream_buffer, uws_client->stream_buffer + consumed_bytes, uws_client->stream_buffer_count - consumed_bytes);
}
uws_client->stream_buffer_count -= consumed_bytes;
}
static void on_underlying_io_close_complete(void* context)
{
if (context == NULL)
{
/* Codes_SRS_UWS_CLIENT_01_477: [ When on_underlying_io_close_complete is called with a NULL context, it shall do nothing. ]*/
LogError("NULL context for on_underlying_io_close_complete");
}
else
{
UWS_CLIENT_HANDLE uws_client = (UWS_CLIENT_HANDLE)context;
if (uws_client->uws_state == UWS_STATE_CLOSING_UNDERLYING_IO)
{
/* Codes_SRS_UWS_CLIENT_01_475: [ When on_underlying_io_close_complete is called while closing the underlying IO a subsequent uws_client_open_async shall succeed. ]*/
indicate_ws_close_complete(uws_client);
uws_client->uws_state = UWS_STATE_CLOSED;
}
}
}
static void on_underlying_io_close_sent(void* context, IO_SEND_RESULT io_send_result)
{
if (context == NULL)
{
/* Codes_SRS_UWS_CLIENT_01_489: [ When on_underlying_io_close_sent is called with NULL context, it shall do nothing. ] */
LogError("NULL context in ");
}
else
{
UWS_CLIENT_INSTANCE* uws_client = (UWS_CLIENT_HANDLE)context;
switch (io_send_result)
{
default:
LogError("Unknown enum value: %d", io_send_result);
break;
case IO_SEND_OK:
case IO_SEND_CANCELLED:
if (uws_client->uws_state == UWS_STATE_CLOSING_SENDING_CLOSE)
{
uws_client->uws_state = UWS_STATE_CLOSING_UNDERLYING_IO;
/* Codes_SRS_UWS_CLIENT_01_490: [ When on_underlying_io_close_sent is called while the uws client is CLOSING, on_underlying_io_close_sent shall close the underlying IO by calling xio_close. ]*/
if (xio_close(uws_client->underlying_io, on_underlying_io_close_complete, uws_client) != 0)
{
/* Codes_SRS_UWS_CLIENT_01_496: [ If the close was initiated by the peer no on_ws_close_complete shall be called. ]*/
indicate_ws_close_complete(uws_client);
}
}
case IO_SEND_ERROR:
break;
}
}
}
/*the following function does the same as sscanf(pos2, "%d", &sec)*/
/*this function only exists because some of platforms do not have sscanf. */
static int ParseStringToDecimal(const char *src, int* dst)
{
int result;
char* next;
(*dst) = (int)strtol(src, &next, 0);
if ((src == next) || ((((*dst) == INT_MAX) || ((*dst) == INT_MIN)) && (errno != 0)))
{
result = MU_FAILURE;
}
else
{
result = 0;
}
return result;
}
/*the following function does the same as sscanf(buf, "HTTP/%*d.%*d %d %*[^\r\n]", &ret) */
/*this function only exists because some of platforms do not have sscanf. This is not a full implementation; it only works with well-defined HTTP response. */
static int ParseHttpResponse(const char* src, int* dst)
{
int result;
static const char HTTPPrefix[] = "HTTP/";
bool fail;
const char* runPrefix;
if ((src == NULL) || (dst == NULL))
{
result = MU_FAILURE;
}
else
{
fail = false;
runPrefix = HTTPPrefix;
while ((*runPrefix) != '\0')
{
if ((*runPrefix) != (*src))
{
fail = true;