-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathNAVFoundation.WebSocket.axi
More file actions
2205 lines (1912 loc) · 81.2 KB
/
NAVFoundation.WebSocket.axi
File metadata and controls
2205 lines (1912 loc) · 81.2 KB
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
PROGRAM_NAME='NAVFoundation.WebSocket'
/*
_ _ _ ___ __
| \ | | ___ _ __ __ _ __ _| |_ ___ / \ \ / /
| \| |/ _ \| '__/ _` |/ _` | __/ _ \ / _ \ \ / /
| |\ | (_) | | | (_| | (_| | || __// ___ \ V /
|_| \_|\___/|_| \__, |\__,_|\__\___/_/ \_\_/
|___/
MIT License
Copyright (c) 2010-2026 Norgate AV
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
*/
#IF_NOT_DEFINED __NAV_FOUNDATION_WEBSOCKET__
#DEFINE __NAV_FOUNDATION_WEBSOCKET__ 'NAVFoundation.WebSocket'
#include 'NAVFoundation.WebSocket.h.axi'
#include 'NAVFoundation.ErrorLogUtils.axi'
#include 'NAVFoundation.StringUtils.axi'
#include 'NAVFoundation.Encoding.axi'
#include 'NAVFoundation.Encoding.Base64.axi'
#include 'NAVFoundation.Encoding.Utf8.axi'
#include 'NAVFoundation.Cryptography.Sha1.axi'
#include 'NAVFoundation.HttpUtils.axi'
#include 'NAVFoundation.Url.axi'
#include 'NAVFoundation.SocketUtils.axi'
// =============================================================================
// WebSocket Send Helper Functions
// =============================================================================
/**
* Sends a pre-built WebSocket frame to a device.
* Internal helper function - users should call NAVWebSocketSend() instead.
*
* @function NAVWebSocketSendFrame
* @access private
* @param {dev} device - The device to send the frame to
* @param {char[]} frame - The frame data to send
* @returns {char} TRUE if sent successfully, FALSE otherwise
*/
define_function char NAVWebSocketSendFrame(dev device, char frame[]) {
stack_var long frameLength
frameLength = length_array(frame)
if (frameLength == 0) {
return false
}
send_string device, frame
return true
}
// =============================================================================
// WebSocket Context Management Functions
// =============================================================================
/**
* Initializes a WebSocket context structure.
*
* @function NAVWebSocketInit
* @access public
* @param {_NAVWebSocket} ws - WebSocket context to initialize
* @param {dev} device - Network device to use for the connection
*
* @example
* stack_var _NAVWebSocket ws
*
* NAVWebSocketInit(ws, dvSocket)
* if (NAVWebSocketConnect(ws, 'ws://localhost:8080')) {
* // TCP connection initiated
* }
*/
define_function NAVWebSocketInit(_NAVWebSocket ws, dev device) {
ws.Device = device
// Initialize URL struct fields
ws.Url.Scheme = ''
ws.Url.Host = ''
ws.Url.Port = 0
ws.Url.Path = ''
ws.Url.FullPath = ''
ws.Url.Fragment = ''
ws.Url.HasUserInfo = false
ws.Url.UserInfo.Username = ''
ws.Url.UserInfo.Password = ''
ws.IsConnected = false
ws.HandshakeRequest = ''
// Initialize RxBuffer
NAVWebSocketBufferInit(ws.RxBuffer)
}
/**
* Connects to a WebSocket server by parsing the URL and opening a TCP socket.
* This handles URL parsing, handshake preparation, and socket connection.
*
* @function NAVWebSocketConnect
* @access public
* @param {_NAVWebSocket} ws - WebSocket context (must be initialized with NAVWebSocketInit)
* @param {char[]} url - Complete WebSocket URL (e.g., 'ws://example.com:8080/socket')
* @returns {char} TRUE if connection initiated successfully, FALSE otherwise
*
* @example
* stack_var _NAVWebSocket ws
*
* NAVWebSocketInit(ws, dvSocket)
* if (NAVWebSocketConnect(ws, 'ws://localhost:8080/chat')) {
* // Connection initiated, wait for NAVWebSocketOnOpenCallback
* }
*/
define_function char NAVWebSocketConnect(_NAVWebSocket ws, char url[]) {
stack_var _NAVUrl parsedUrl
// Don't connect if already connected
if (NAVWebSocketIsOpen(ws)) {
NAVLibraryFunctionErrorLog(NAV_LOG_LEVEL_WARNING,
__NAV_FOUNDATION_WEBSOCKET__,
'NAVWebSocketConnect',
'WebSocket is already connected')
return false
}
if (!NAVParseUrl(url, parsedUrl)) {
NAVLibraryFunctionErrorLog(NAV_LOG_LEVEL_ERROR,
__NAV_FOUNDATION_WEBSOCKET__,
'NAVWebSocketConnect',
'Failed to parse URL')
return false
}
// Store parsed URL
ws.Url = parsedUrl
if (!NAVWebSocketBuildHandshakeRequest(url, ws.HandshakeRequest, ws.RxBuffer.HandshakeKey)) {
NAVLibraryFunctionErrorLog(NAV_LOG_LEVEL_ERROR,
__NAV_FOUNDATION_WEBSOCKET__,
'NAVWebSocketConnect',
'Failed to build handshake request')
return false
}
// DEBUG: Log the handshake request
NAVLibraryFunctionErrorLog(NAV_LOG_LEVEL_DEBUG,
__NAV_FOUNDATION_WEBSOCKET__,
'NAVWebSocketConnect',
"'Handshake request (', itoa(length_array(ws.HandshakeRequest)), ' bytes)'")
NAVLibraryFunctionErrorLog(NAV_LOG_LEVEL_DEBUG,
__NAV_FOUNDATION_WEBSOCKET__,
'NAVWebSocketConnect',
"'Request: ', ws.HandshakeRequest")
// Open TCP or TLS connection based on URL scheme
switch (ws.Url.Scheme) {
case NAV_URL_SCHEME_WS: {
stack_var slong result
result = NAVClientSocketOpen(ws.Device.PORT, ws.Url.Host, ws.Url.Port, IP_TCP)
if (result < 0) {
NAVLibraryFunctionErrorLog(NAV_LOG_LEVEL_ERROR,
__NAV_FOUNDATION_WEBSOCKET__,
'NAVWebSocketConnect',
"'Failed to open socket to ', ws.Url.Host, ':', itoa(ws.Url.Port)")
return false
}
}
case NAV_URL_SCHEME_WSS: {
stack_var slong result
result = NAVClientTlsSocketOpen(ws.Device.PORT,
ws.Url.Host,
ws.Url.Port,
TLS_VALIDATE_CERTIFICATE)
if (result < 0) {
NAVLibraryFunctionErrorLog(NAV_LOG_LEVEL_ERROR,
__NAV_FOUNDATION_WEBSOCKET__,
'NAVWebSocketConnect',
"'Failed to open TLS socket to ', ws.Url.Host, ':', itoa(ws.Url.Port)")
return false
}
}
default: {
NAVLibraryFunctionErrorLog(NAV_LOG_LEVEL_ERROR,
__NAV_FOUNDATION_WEBSOCKET__,
'NAVWebSocketConnect',
"'Unsupported URL scheme: ', ws.Url.Scheme")
return false
}
}
return true
}
/**
* Handles TCP connection establishment and sends the WebSocket handshake.
* Call this from the data_event online handler after TCP connects.
*
* @function NAVWebSocketOnConnect
* @access public
* @param {_NAVWebSocket} ws - WebSocket context
*
* @example
* data_event[dvWebSocket] {
* online: {
* NAVWebSocketOnConnect(ws)
* }
* }
*/
define_function NAVWebSocketOnConnect(_NAVWebSocket ws) {
ws.IsConnected = true
ws.RxBuffer.State = NAV_WEBSOCKET_STATE_CONNECTING
NAVWebSocketSendFrame(ws.Device, ws.HandshakeRequest)
}
/**
* Handles TCP disconnection and cleans up WebSocket state.
* Call this from the data_event offline or onerror handler.
*
* @function NAVWebSocketOnDisconnect
* @access public
* @param {_NAVWebSocket} ws - WebSocket context
*
* @example
* data_event[dvWebSocket] {
* offline: {
* NAVWebSocketOnDisconnect(ws)
* }
* onerror: {
* NAVWebSocketOnDisconnect(ws)
* }
* }
*/
define_function NAVWebSocketOnDisconnect(_NAVWebSocket ws) {
ws.IsConnected = false
ws.RxBuffer.State = NAV_WEBSOCKET_STATE_IDLE
}
/**
* Handles TCP errors and cleans up WebSocket state.
* Call this from the data_event onerror handler.
*
* @function NAVWebSocketOnError
* @access public
* @param {_NAVWebSocket} ws - WebSocket context
*
* @example
* data_event[dvWebSocket] {
* onerror: {
* NAVWebSocketOnError(ws)
* }
* }
*/
define_function NAVWebSocketOnError(_NAVWebSocket ws) {
// For now, just handle like a disconnect
// Future: could add error-specific handling, retry logic, etc.
NAVWebSocketOnDisconnect(ws)
}
/**
* Checks if a WebSocket is in OPEN state (RFC 6455 readyState OPEN).
* Returns TRUE only when both TCP socket is connected AND handshake is complete.
*
* @function NAVWebSocketIsOpen
* @access public
* @param {_NAVWebSocket} ws - WebSocket context to check
* @returns {char} TRUE if in OPEN state (ready to send/receive data), FALSE otherwise
*/
define_function char NAVWebSocketIsOpen(_NAVWebSocket ws) {
return ws.IsConnected && ws.RxBuffer.State == NAV_WEBSOCKET_STATE_OPEN
}
/**
* Sends data (text or binary) over an established WebSocket connection.
* Data is automatically framed as a text frame (opcode 0x01) and masked.
*
* @function NAVWebSocketSend
* @access public
* @param {_NAVWebSocket} ws - WebSocket context
* @param {char[]} data - Data to send (text string or binary bytes)
* @returns {char} TRUE if sent successfully, FALSE otherwise
*
* @example
* stack_var _NAVWebSocket ws
*
* // Only send when in OPEN state
* if (NAVWebSocketIsOpen(ws)) {
* NAVWebSocketSend(ws, 'Hello from NetLinx!')
* }
*/
define_function char NAVWebSocketSend(_NAVWebSocket ws, char data[]) {
stack_var char frame[65535]
if (!NAVWebSocketIsOpen(ws)) {
NAVLibraryFunctionErrorLog(NAV_LOG_LEVEL_WARNING,
__NAV_FOUNDATION_WEBSOCKET__,
'NAVWebSocketSend',
'WebSocket not ready')
return false
}
if (!NAVWebSocketBuildTextFrame(data, NAV_WEBSOCKET_MASKED, frame)) {
NAVLibraryFunctionErrorLog(NAV_LOG_LEVEL_ERROR,
__NAV_FOUNDATION_WEBSOCKET__,
'NAVWebSocketSend',
'Failed to build text frame')
return false
}
return NAVWebSocketSendFrame(ws.Device, frame)
}
/**
* Sends a ping frame over an established WebSocket connection.
* Internal function - ping/pong is handled automatically by the library.
*
* @function NAVWebSocketSendPing
* @access private
* @param {_NAVWebSocket} ws - WebSocket context
* @param {char[]} payload - Optional ping payload (max 125 bytes)
* @returns {char} TRUE if sent successfully, FALSE otherwise
*
* @example
* stack_var _NAVWebSocket ws
*
* if (NAVWebSocketIsOpen(ws)) {
* NAVWebSocketSendPing(ws, 'ping')
* }
*/
define_function char NAVWebSocketSendPing(_NAVWebSocket ws, char payload[]) {
stack_var char frame[150]
if (!NAVWebSocketIsOpen(ws)) {
NAVLibraryFunctionErrorLog(NAV_LOG_LEVEL_WARNING,
__NAV_FOUNDATION_WEBSOCKET__,
'NAVWebSocketSendPing',
'WebSocket not ready')
return false
}
if (!NAVWebSocketBuildPingFrame(payload, NAV_WEBSOCKET_MASKED, frame)) {
NAVLibraryFunctionErrorLog(NAV_LOG_LEVEL_ERROR,
__NAV_FOUNDATION_WEBSOCKET__,
'NAVWebSocketSendPing',
'Failed to build ping frame')
return false
}
return NAVWebSocketSendFrame(ws.Device, frame)
}
/**
* Sends a close frame with custom status code and reason.
* For advanced use cases where you need to signal specific close reasons.
*
* @function NAVWebSocketSendClose
* @access public
* @param {_NAVWebSocket} ws - WebSocket context
* @param {integer} statusCode - Close status code (see NAV_WEBSOCKET_CLOSE_* constants)
* @param {char[]} reason - Optional human-readable reason (max 123 bytes)
* @returns {char} TRUE if close frame sent successfully, FALSE otherwise
*
* @example
* stack_var _NAVWebSocket ws
*
* // Signal protocol error
* NAVWebSocketSendClose(ws, NAV_WEBSOCKET_CLOSE_PROTOCOL_ERROR, 'Invalid frame received')
*
* @note For normal closes, use NAVWebSocketClose(ws) instead
*/
define_function char NAVWebSocketSendClose(_NAVWebSocket ws, integer statusCode, char reason[]) {
stack_var char frame[150]
stack_var char result
// Don't close if not connected
if (!NAVWebSocketIsOpen(ws)) {
NAVLibraryFunctionErrorLog(NAV_LOG_LEVEL_WARNING,
__NAV_FOUNDATION_WEBSOCKET__,
'NAVWebSocketSendClose',
'WebSocket is not connected')
return false
}
result = true
if (ws.RxBuffer.State == NAV_WEBSOCKET_STATE_OPEN) {
if (NAVWebSocketBuildCloseFrame(statusCode, reason, NAV_WEBSOCKET_MASKED, frame)) {
result = NAVWebSocketSendFrame(ws.Device, frame)
}
// RFC 6455 §7.1.3: Enter CLOSING state and wait for server's close frame
// The actual TCP close happens when we receive the server's close frame
ws.RxBuffer.State = NAV_WEBSOCKET_STATE_CLOSING
}
else {
// If not connected, close immediately
ws.IsConnected = false
ws.RxBuffer.State = NAV_WEBSOCKET_STATE_CLOSED
ws.RxBuffer.HandshakeData = ''
// Close the underlying socket
NAVWebSocketCloseSocket(ws)
}
return result
}
/**
* Closes the WebSocket connection with a normal close status.
* This is the simple version for most use cases.
*
* @function NAVWebSocketClose
* @access public
* @param {_NAVWebSocket} ws - WebSocket context
* @returns {char} TRUE if close frame sent successfully, FALSE otherwise
*
* @example
* stack_var _NAVWebSocket ws
*
* NAVWebSocketClose(ws)
*
* @note For advanced close with custom code/reason, use NAVWebSocketSendClose()
*/
define_function char NAVWebSocketClose(_NAVWebSocket ws) {
return NAVWebSocketSendClose(ws, NAV_WEBSOCKET_CLOSE_NORMAL, '')
}
/**
* Processes incoming data in a WebSocket connection.
* Call this from your data_event[device].string handler.
*
* @function NAVWebSocketProcessData
* @access private
* @deprecated Use NAVWebSocketProcessBuffer() instead - this is a legacy function
* @param {_NAVWebSocket} ws - WebSocket context
* @param {char[]} data - Incoming data from the socket
* @returns {char} TRUE if processing completed, FALSE if an error occurred
*
* @note Handles handshake validation (transitions CONNECTING → OPEN)
* @note After handshake, frames are automatically buffered via create_buffer
*
* @example
* data_event[dvSocket] {
* string: {
* if (!NAVWebSocketProcessData(ws, data.text)) {
* // Handle error
* }
* }
* }
*/
define_function char NAVWebSocketProcessData(_NAVWebSocket ws, char data[]) {
// After handshake, just buffer incoming frame data
if (ws.RxBuffer.State == NAV_WEBSOCKET_STATE_OPEN) {
// Data is automatically buffered via create_buffer
return true
}
// Accumulate handshake response
ws.RxBuffer.HandshakeData = "ws.RxBuffer.HandshakeData, data"
// Wait for complete HTTP response (ends with double CRLF)
if (!NAVContains(ws.RxBuffer.HandshakeData, "NAV_CR, NAV_LF, NAV_CR, NAV_LF")) {
return true
}
// Validate the handshake response
if (!NAVWebSocketValidateHandshakeResponse(ws.RxBuffer.HandshakeData, ws.RxBuffer.HandshakeKey)) {
NAVLibraryFunctionErrorLog(NAV_LOG_LEVEL_ERROR,
__NAV_FOUNDATION_WEBSOCKET__,
'NAVWebSocketProcessData',
'Handshake validation failed')
return false
}
// Handshake successful
ws.RxBuffer.State = NAV_WEBSOCKET_STATE_OPEN
ws.RxBuffer.HandshakeData = ''
return true
}
/**
* Parses the next frame from the WebSocket receive buffer.
* Call this repeatedly until it returns NAV_WEBSOCKET_ERROR_INCOMPLETE.
*
* @function NAVWebSocketGetNextFrame
* @access private
* @param {_NAVWebSocket} ws - WebSocket context
* @param {_NAVWebSocketFrameParseResult} result - Parse result with frame data
* @returns {char} TRUE if a frame was parsed, FALSE if incomplete or error
*
* @example
* stack_var _NAVWebSocket ws
* stack_var _NAVWebSocketFrameParseResult result
*
* while (NAVWebSocketGetNextFrame(ws, result)) {
* switch (result.Frame.Opcode) {
* case NAV_WEBSOCKET_OPCODE_TEXT: {
* // Handle text message
* }
* case NAV_WEBSOCKET_OPCODE_PING: {
* // Send pong response
* }
* }
* }
*/
define_function char NAVWebSocketGetNextFrame(_NAVWebSocket ws, _NAVWebSocketFrameParseResult result) {
stack_var char temp[65535]
if (NAVWebSocketParseFrame(ws.RxBuffer.Data, result) != NAV_WEBSOCKET_SUCCESS) {
return false
}
if (result.BytesConsumed > 0) {
temp = NAVStringSubstring(ws.RxBuffer.Data, type_cast(result.BytesConsumed + 1), 0)
ws.RxBuffer.Data = temp
}
return true
}
// =============================================================================
// WebSocket Handshake Functions
// =============================================================================
/**
* Builds a WebSocket handshake request (HTTP Upgrade request).
*
* @function NAVWebSocketBuildHandshakeRequest
* @access private
* @param {char[]} url - Complete WebSocket URL (e.g., 'ws://example.com:8080/socket')
* @param {char[]} output - Output buffer to write the HTTP request to
* @param {char[16]} key - Output array to store the generated Sec-WebSocket-Key for validation
* @returns {char} TRUE if successful, FALSE otherwise
*
* @example
* stack_var char request[2000]
* stack_var char key[16]
*
* if (NAVWebSocketBuildHandshakeRequest('ws://example.com:8080/socket', request, key)) {
* send_string dvSocket, request
* // Save 'key' for later validation of server response
* }
*
* @note The key parameter receives the 16-byte key needed to validate the server's response
* @note URL scheme can be 'ws://' or 'wss://' (converted to http/https internally)
*/
define_function char NAVWebSocketBuildHandshakeRequest(char url[], char output[], char key[16]) {
stack_var integer i
stack_var char base64Key[NAV_MAX_BUFFER]
stack_var _NAVHttpRequest request
stack_var _NAVUrl parsedUrl
// Parse the URL
if (!NAVParseUrl(url, parsedUrl)) {
NAVLibraryFunctionErrorLog(NAV_LOG_LEVEL_ERROR,
__NAV_FOUNDATION_WEBSOCKET__,
'NAVWebSocketBuildHandshakeRequest',
"'Failed to parse WebSocket URL: ', url")
return false
}
// Convert ws/wss schemes to http/https for HTTP request
switch (parsedUrl.Scheme) {
case NAV_URL_SCHEME_WS: {
parsedUrl.Scheme = NAV_URL_SCHEME_HTTP
}
case NAV_URL_SCHEME_WSS: {
parsedUrl.Scheme = NAV_URL_SCHEME_HTTPS
}
case NAV_URL_SCHEME_HTTP:
case NAV_URL_SCHEME_HTTPS: {
// Supported schemes
}
default: {
NAVLibraryFunctionErrorLog(NAV_LOG_LEVEL_ERROR,
__NAV_FOUNDATION_WEBSOCKET__,
'NAVWebSocketBuildHandshakeRequest',
"'Unsupported URL scheme for WebSocket: ', parsedUrl.Scheme")
return false
}
}
// Generate random 16-byte key
for (i = 1; i <= 16; i++) {
key[i] = type_cast(random_number(256) - 1)
}
// Base64 encode the key
set_length_array(key, 16)
base64Key = NAVBase64Encode(key)
// Initialize HTTP request
if (!NAVHttpRequestInit(request, NAV_HTTP_METHOD_GET, parsedUrl, '')) {
NAVLibraryFunctionErrorLog(NAV_LOG_LEVEL_ERROR,
__NAV_FOUNDATION_WEBSOCKET__,
'NAVWebSocketBuildHandshakeRequest',
"'Failed to initialize HTTP request for WebSocket handshake'")
return false
}
// Add WebSocket-specific headers
if (!NAVHttpRequestAddHeader(request, NAV_HTTP_HEADER_UPGRADE, 'websocket')) {
NAVLibraryFunctionErrorLog(NAV_LOG_LEVEL_ERROR,
__NAV_FOUNDATION_WEBSOCKET__,
'NAVWebSocketBuildHandshakeRequest',
"'Failed to add Upgrade header'")
return false
}
if (!NAVHttpRequestAddHeader(request, NAV_HTTP_HEADER_CONNECTION, NAV_HTTP_CONNECTION_UPGRADE)) {
NAVLibraryFunctionErrorLog(NAV_LOG_LEVEL_ERROR,
__NAV_FOUNDATION_WEBSOCKET__,
'NAVWebSocketBuildHandshakeRequest',
"'Failed to add Connection header'")
return false
}
if (!NAVHttpRequestAddHeader(request, NAV_HTTP_HEADER_SEC_WEBSOCKET_KEY, base64Key)) {
NAVLibraryFunctionErrorLog(NAV_LOG_LEVEL_ERROR,
__NAV_FOUNDATION_WEBSOCKET__,
'NAVWebSocketBuildHandshakeRequest',
"'Failed to add Sec-WebSocket-Key header'")
return false
}
if (!NAVHttpRequestAddHeader(request, NAV_HTTP_HEADER_SEC_WEBSOCKET_VERSION, NAV_HTTP_WEBSOCKET_VERSION)) {
NAVLibraryFunctionErrorLog(NAV_LOG_LEVEL_ERROR,
__NAV_FOUNDATION_WEBSOCKET__,
'NAVWebSocketBuildHandshakeRequest',
"'Failed to add Sec-WebSocket-Version header'")
return false
}
// Build the complete HTTP request
if (!NAVHttpBuildRequest(request, output)) {
NAVLibraryFunctionErrorLog(NAV_LOG_LEVEL_ERROR,
__NAV_FOUNDATION_WEBSOCKET__,
'NAVWebSocketBuildHandshakeRequest',
"'Failed to build HTTP request'")
return false
}
return true
}
/**
* Validates a WebSocket handshake response from the server.
*
* @function NAVWebSocketValidateHandshakeResponse
* @access private
* @param {char[]} response - The complete HTTP response from the server
* @param {char[16]} key - The original 16-byte key sent in the request
* @returns {char} TRUE if valid, FALSE otherwise
*
* @example
* stack_var char key[16]
*
* // key was saved from NAVWebSocketBuildHandshakeRequest
* if (NAVWebSocketValidateHandshakeResponse(serverResponse, key)) {
* // Handshake successful, can now send/receive WebSocket frames
* }
*
* @note This validates the HTTP 101 status and Sec-WebSocket-Accept header
*/
define_function char NAVWebSocketValidateHandshakeResponse(char response[], char key[16]) {
stack_var char base64Key[NAV_MAX_BUFFER]
stack_var char concatenated[NAV_MAX_BUFFER]
stack_var char sha1Hash[20]
stack_var char expectedAccept[NAV_MAX_BUFFER]
stack_var char actualAccept[NAV_MAX_BUFFER]
stack_var _NAVHttpResponse httpResponse
stack_var integer i
// DEBUG: Log raw response
NAVLibraryFunctionErrorLog(NAV_LOG_LEVEL_DEBUG,
__NAV_FOUNDATION_WEBSOCKET__,
'NAVWebSocketValidateHandshakeResponse',
"'Raw response (', itoa(length_array(response)), ' bytes)'")
NAVLibraryFunctionErrorLog(NAV_LOG_LEVEL_DEBUG,
__NAV_FOUNDATION_WEBSOCKET__,
'NAVWebSocketValidateHandshakeResponse',
"'Response: ', response")
// Initialize response structure
NAVHttpResponseInit(httpResponse)
// Parse response headers (includes status line parsing)
if (!NAVHttpParseResponse(response, httpResponse)) {
NAVLibraryFunctionErrorLog(NAV_LOG_LEVEL_DEBUG,
__NAV_FOUNDATION_WEBSOCKET__,
'NAVWebSocketValidateHandshakeResponse',
'Failed to parse HTTP response')
return false
}
// DEBUG: Log parsed status
NAVLibraryFunctionErrorLog(NAV_LOG_LEVEL_DEBUG,
__NAV_FOUNDATION_WEBSOCKET__,
'NAVWebSocketValidateHandshakeResponse',
"'Status: ', itoa(httpResponse.Status.Code), ' ', httpResponse.Status.Message")
NAVLibraryFunctionErrorLog(NAV_LOG_LEVEL_DEBUG,
__NAV_FOUNDATION_WEBSOCKET__,
'NAVWebSocketValidateHandshakeResponse',
"'Header count: ', itoa(httpResponse.Headers.Count)")
// DEBUG: Log all headers
for (i = 1; i <= httpResponse.Headers.Count; i++) {
NAVLibraryFunctionErrorLog(NAV_LOG_LEVEL_DEBUG,
__NAV_FOUNDATION_WEBSOCKET__,
'NAVWebSocketValidateHandshakeResponse',
"'Header[', itoa(i), ']: ', httpResponse.Headers.Headers[i].Key, ': ', httpResponse.Headers.Headers[i].Value")
}
// Verify status code is 101 Switching Protocols
if (httpResponse.Status.Code != NAV_HTTP_STATUS_CODE_INFO_SWITCHING_PROTOCOLS) {
NAVLibraryFunctionErrorLog(NAV_LOG_LEVEL_DEBUG,
__NAV_FOUNDATION_WEBSOCKET__,
'NAVWebSocketValidateHandshakeResponse',
"'Invalid status code: ', itoa(httpResponse.Status.Code), ' (expected 101)'")
return false
}
// Base64 encode the original key
base64Key = NAVBase64Encode(key)
if (!length_array(base64Key)) {
NAVLibraryFunctionErrorLog(NAV_LOG_LEVEL_ERROR,
__NAV_FOUNDATION_WEBSOCKET__,
'NAVWebSocketValidateHandshakeResponse',
'Failed to Base64 encode key')
return false
}
NAVLibraryFunctionErrorLog(NAV_LOG_LEVEL_DEBUG,
__NAV_FOUNDATION_WEBSOCKET__,
'NAVWebSocketValidateHandshakeResponse',
"'Base64 key: ', base64Key")
// Concatenate with WebSocket GUID
concatenated = "base64Key, NAV_WEBSOCKET_GUID"
// SHA-1 hash the concatenated string
sha1Hash = NAVSha1GetHash(concatenated)
if (!length_array(sha1Hash)) {
NAVLibraryFunctionErrorLog(NAV_LOG_LEVEL_ERROR,
__NAV_FOUNDATION_WEBSOCKET__,
'NAVWebSocketValidateHandshakeResponse',
'Failed to generate SHA-1 hash')
return false
}
// Base64 encode the hash
expectedAccept = NAVBase64Encode(sha1Hash)
if (!length_array(expectedAccept)) {
NAVLibraryFunctionErrorLog(NAV_LOG_LEVEL_ERROR,
__NAV_FOUNDATION_WEBSOCKET__,
'NAVWebSocketValidateHandshakeResponse',
'Failed to Base64 encode SHA-1 hash')
return false
}
NAVLibraryFunctionErrorLog(NAV_LOG_LEVEL_DEBUG,
__NAV_FOUNDATION_WEBSOCKET__,
'NAVWebSocketValidateHandshakeResponse',
"'Expected Accept: ', expectedAccept")
// Check if Sec-WebSocket-Accept header exists
if (!NAVHttpHeaderKeyExists(httpResponse.Headers, NAV_HTTP_HEADER_SEC_WEBSOCKET_ACCEPT)) {
NAVLibraryFunctionErrorLog(NAV_LOG_LEVEL_ERROR,
__NAV_FOUNDATION_WEBSOCKET__,
'NAVWebSocketValidateHandshakeResponse',
'Sec-WebSocket-Accept header not found')
return false
}
// Get Sec-WebSocket-Accept header value
actualAccept = NAVHttpGetHeaderValue(httpResponse.Headers, NAV_HTTP_HEADER_SEC_WEBSOCKET_ACCEPT)
NAVLibraryFunctionErrorLog(NAV_LOG_LEVEL_DEBUG,
__NAV_FOUNDATION_WEBSOCKET__,
'NAVWebSocketValidateHandshakeResponse',
"'Actual Accept: ', actualAccept")
// Compare expected and actual
if (actualAccept != expectedAccept) {
NAVLibraryFunctionErrorLog(NAV_LOG_LEVEL_DEBUG,
__NAV_FOUNDATION_WEBSOCKET__,
'NAVWebSocketValidateHandshakeResponse',
'Sec-WebSocket-Accept mismatch')
return false
}
return true
}
// =============================================================================
// Utility Functions
// =============================================================================
/**
* Validates a close status code per RFC 6455 §7.4.
* Checks that the code is in a valid range and not reserved.
*
* @function NAVWebSocketIsValidCloseCode
* @access private
* @param {integer} code - The close status code to validate
* @returns {char} TRUE if valid, FALSE if invalid/reserved
*
* @example
* if (!NAVWebSocketIsValidCloseCode(statusCode)) {
* // Invalid close code
* }
*/
define_function char NAVWebSocketIsValidCloseCode(integer code) {
// 0-999: Not used
if (code < 1000) {
return false
}
// 1000-2999: Reserved by RFC
if (code >= 1000 && code <= 2999) {
// These codes cannot appear on the wire (RFC 6455 §7.4.1)
if (code == 1004 || code == 1005 || code == 1006 || code == 1015) {
return false
}
// Valid protocol codes: 1000-1003, 1007-1011
return true
}
// 3000-3999: Registered with IANA (valid)
if (code >= 3000 && code <= 3999) {
return true
}
// 4000-4999: Private use (valid)
if (code >= 4000 && code <= 4999) {
return true
}
// 5000+: Invalid
return false
}
/**
* Closes the underlying socket (TCP or TLS) based on the WebSocket URL scheme.
*
* @function NAVWebSocketCloseSocket
* @access private
* @param {_NAVWebSocket} ws - WebSocket context
*
* @example
* NAVWebSocketCloseSocket(ws)
*/
define_function NAVWebSocketCloseSocket(_NAVWebSocket ws) {
switch (ws.Url.Scheme) {
case NAV_URL_SCHEME_WS: {
NAVClientSocketClose(ws.Device.PORT)
}
case NAV_URL_SCHEME_WSS: {
NAVClientTlsSocketClose(ws.Device.PORT)
}
}
}
/**
* Checks if a given opcode represents a control frame.
*
* @function NAVWebSocketIsControlFrame
* @access private
* @param {integer} opcode - The opcode to check
* @returns {char} 1 if the opcode is a control frame (close, ping, pong), 0 otherwise
*
* @example
* if (NAVWebSocketIsControlFrame(NAV_WEBSOCKET_OPCODE_PING)) {
* // Handle control frame
* }
*/
define_function char NAVWebSocketIsControlFrame(integer opcode) {
return (opcode >= NAV_WEBSOCKET_OPCODE_CLOSE && opcode <= NAV_WEBSOCKET_OPCODE_PONG)
}
/**
* Validates that an opcode is defined and valid according to RFC 6455.
*
* @function NAVWebSocketIsValidOpcode
* @access private
* @param {integer} opcode - The opcode to validate
* @returns {char} 1 if the opcode is valid, 0 otherwise
*
* @example
* if (!NAVWebSocketIsValidOpcode(frame.Opcode)) {
* // Handle invalid opcode
* }
*/
define_function char NAVWebSocketIsValidOpcode(integer opcode) {
switch (opcode) {
case NAV_WEBSOCKET_OPCODE_CONTINUATION:
case NAV_WEBSOCKET_OPCODE_TEXT:
case NAV_WEBSOCKET_OPCODE_BINARY:
case NAV_WEBSOCKET_OPCODE_CLOSE:
case NAV_WEBSOCKET_OPCODE_PING:
case NAV_WEBSOCKET_OPCODE_PONG: {
return true
}
default: {
return false
}
}
}
/**
* Generates a random 4-byte masking key for WebSocket frame masking.
*
* @function NAVWebSocketGenerateMaskingKey
* @access private
* @param {char[4]} key - Output array to store the generated masking key
*
* @example
* stack_var char maskingKey[4]
* NAVWebSocketGenerateMaskingKey(maskingKey)
*/
define_function NAVWebSocketGenerateMaskingKey(char key[4]) {
stack_var integer i
for (i = 1; i <= NAV_WEBSOCKET_MASKING_KEY_LENGTH; i++) {
key[i] = type_cast(random_number(256) - 1)
}
set_length_array(key, NAV_WEBSOCKET_MASKING_KEY_LENGTH)
}
/**
* Applies or removes WebSocket masking using XOR operation.
* This function works for both masking and unmasking since XOR is reversible.
*
* @function NAVWebSocketMaskData
* @access private
* @param {char[]} data - The data to mask or unmask
* @param {char[4]} maskingKey - The 4-byte masking key
* @param {char[]} output - Output buffer to store the masked/unmasked data
* @returns {long} The length of the processed data
*
* @example
* stack_var char masked[1000]
* stack_var char maskingKey[4]
* stack_var long length
*
* NAVWebSocketGenerateMaskingKey(maskingKey)
* length = NAVWebSocketMaskData(payload, maskingKey, masked)
*/
define_function long NAVWebSocketMaskData(char data[], char maskingKey[4], char output[]) {
stack_var long i
stack_var long length
length = length_array(data)
for (i = 1; i <= length; i++) {
output[i] = data[i] bxor maskingKey[((i - 1) % NAV_WEBSOCKET_MASKING_KEY_LENGTH) + 1]
}
return length
}
// =============================================================================
// Frame Validation Functions
// =============================================================================
/**