forked from me-no-dev/ESPAsyncWebServer
-
Notifications
You must be signed in to change notification settings - Fork 97
Expand file tree
/
Copy pathAsyncWebSocket.cpp
More file actions
1535 lines (1335 loc) · 45.3 KB
/
AsyncWebSocket.cpp
File metadata and controls
1535 lines (1335 loc) · 45.3 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
// SPDX-License-Identifier: LGPL-3.0-or-later
// Copyright 2016-2026 Hristo Gochkov, Mathieu Carbou, Emil Muratov, Will Miles
#include "AsyncWebSocket.h"
#include "AsyncWebServerLogging.h"
#include <libb64/cencode.h>
#if defined(ESP32)
#if ESP_IDF_VERSION_MAJOR < 5
#include "BackPort_SHA1Builder.h"
#else
#include <SHA1Builder.h>
#endif
#include <rom/ets_sys.h>
#elif defined(TARGET_RP2040) || defined(TARGET_RP2350) || defined(PICO_RP2040) || defined(PICO_RP2350) || defined(ESP8266)
#include <Hash.h>
#elif defined(LIBRETINY)
#include <mbedtls/sha1.h>
#endif
#include <algorithm>
#include <cstdio>
#include <cstring>
#include <memory>
#include <utility>
#define STATE_FRAME_START 0
#define STATE_FRAME_MASK 1
#define STATE_FRAME_DATA 2
using namespace asyncsrv;
size_t webSocketSendFrameWindow(AsyncClient *client) {
if (!client || !client->canSend()) {
return 0;
}
size_t space = client->space();
if (space < 9) {
return 0;
}
return space - 8;
}
size_t webSocketSendFrame(AsyncClient *client, bool final, uint8_t opcode, bool mask, uint8_t *data, size_t len) {
if (!client || !client->canSend()) {
// Serial.println("SF 1");
return 0;
}
size_t space = client->space();
if (space < 2) {
// Serial.println("SF 2");
return 0;
}
uint8_t mbuf[4] = {0, 0, 0, 0};
uint8_t headLen = 2;
if (len && mask) {
headLen += 4;
mbuf[0] = rand() % 0xFF; // NOLINT(runtime/threadsafe_fn)
mbuf[1] = rand() % 0xFF; // NOLINT(runtime/threadsafe_fn)
mbuf[2] = rand() % 0xFF; // NOLINT(runtime/threadsafe_fn)
mbuf[3] = rand() % 0xFF; // NOLINT(runtime/threadsafe_fn)
}
if (len > 125) {
headLen += 2;
}
if (space < headLen) {
// Serial.println("SF 2");
return 0;
}
space -= headLen;
if (len > space) {
len = space;
}
uint8_t *buf = (uint8_t *)malloc(headLen);
if (buf == NULL) {
async_ws_log_e("Failed to allocate");
client->abort();
return 0;
}
buf[0] = opcode & 0x0F;
if (final) {
buf[0] |= 0x80;
}
if (len < 126) {
buf[1] = len & 0x7F;
} else {
buf[1] = 126;
buf[2] = (uint8_t)((len >> 8) & 0xFF);
buf[3] = (uint8_t)(len & 0xFF);
}
if (len && mask) {
buf[1] |= 0x80;
memcpy(buf + (headLen - 4), mbuf, 4);
}
if (client->add((const char *)buf, headLen) != headLen) {
// os_printf("error adding %lu header bytes\n", headLen);
free(buf);
// Serial.println("SF 4");
return 0;
}
free(buf);
if (len) {
if (len && mask) {
size_t i;
for (i = 0; i < len; i++) {
data[i] = data[i] ^ mbuf[i % 4];
}
}
if (client->add((const char *)data, len) != len) {
// os_printf("error adding %lu data bytes\n", len);
// Serial.println("SF 5");
return 0;
}
}
if (!client->send()) {
// os_printf("error sending frame: %lu\n", headLen+len);
// Serial.println("SF 6");
return 0;
}
// Serial.println("SF");
return len;
}
size_t AsyncWebSocketControl::send(AsyncClient *client) {
_finished = true;
return webSocketSendFrame(client, true, _opcode & 0x0F, _mask, _data, _len);
}
/*
* AsyncWebSocketMessageBuffer
*/
AsyncWebSocketMessageBuffer::AsyncWebSocketMessageBuffer(const uint8_t *data, size_t size) : _buffer(std::make_shared<std::vector<uint8_t>>(size)) {
if (_buffer->capacity() < size) {
_buffer->reserve(size);
} else {
std::memcpy(_buffer->data(), data, size);
}
}
AsyncWebSocketMessageBuffer::AsyncWebSocketMessageBuffer(size_t size) : _buffer(std::make_shared<std::vector<uint8_t>>(size)) {
if (_buffer->capacity() < size) {
_buffer->reserve(size);
}
}
bool AsyncWebSocketMessageBuffer::reserve(size_t size) {
if (_buffer->capacity() >= size) {
return true;
}
_buffer->reserve(size);
return _buffer->capacity() >= size;
}
/*
* AsyncWebSocketMessage Message
*/
AsyncWebSocketMessage::AsyncWebSocketMessage(AsyncWebSocketSharedBuffer buffer, uint8_t opcode, bool mask)
: _WSbuffer{buffer}, _opcode(opcode & 0x07), _mask{mask}, _status{_WSbuffer ? WS_MSG_SENDING : WS_MSG_ERROR} {}
size_t AsyncWebSocketMessage::ack(size_t len, uint32_t time) {
(void)time;
const size_t pending = std::min(len, _ack - _acked);
_acked += pending;
if (_sent >= _WSbuffer->size() && _acked >= _ack) {
_status = WS_MSG_SENT;
}
const size_t remaining = len - pending;
async_ws_log_v("ACK[%" PRIu8 "] %u/%u (acked: %u/%u) => %" PRIu8, _opcode, _sent, _WSbuffer->size(), _acked, _ack, static_cast<uint8_t>(_status));
return remaining;
}
size_t AsyncWebSocketMessage::send(AsyncClient *client) {
if (!client) {
async_ws_log_v("No client");
return 0;
}
if (_status != WS_MSG_SENDING) {
async_ws_log_v("SEND[%" PRIu8 "] => [%" PRIu16 "] WS_MSG_SENDING != %" PRIu8, _opcode, client->remotePort(), static_cast<uint8_t>(_status));
return 0;
}
if (_sent == _WSbuffer->size()) {
if (_acked == _ack) {
_status = WS_MSG_SENT;
}
async_ws_log_v("SEND[%" PRIu8 "] => [%" PRIu16 "] WS_MSG_SENT %u/%u (acked: %u/%u)", _opcode, client->remotePort(), _sent, _WSbuffer->size(), _acked, _ack);
return 0;
}
if (_sent > _WSbuffer->size()) {
_status = WS_MSG_ERROR;
async_ws_log_v(
"SEND[%" PRIu8 "] => [%" PRIu16 "] WS_MSG_ERROR %u/%u (acked: %u/%u)", _opcode, client->remotePort(), _sent, _WSbuffer->size(), _acked, _ack
);
return 0;
}
size_t toSend = _WSbuffer->size() - _sent;
const size_t window = webSocketSendFrameWindow(client);
// not enough space in lwip buffer ?
if (!window) {
async_ws_log_v("SEND[%" PRIu8 "] => [%" PRIu16 "] NO_SPACE %u", _opcode, client->remotePort(), toSend);
return 0;
}
toSend = std::min(toSend, window);
_sent += toSend;
_ack += toSend + ((toSend < 126) ? 2 : 4) + (_mask * 4);
bool final = (_sent == _WSbuffer->size());
uint8_t *dPtr = (uint8_t *)(_WSbuffer->data() + (_sent - toSend));
uint8_t opCode = (toSend && _sent == toSend) ? _opcode : (uint8_t)WS_CONTINUATION;
size_t sent = webSocketSendFrame(client, final, opCode, _mask, dPtr, toSend);
_status = WS_MSG_SENDING;
if (toSend && sent != toSend) {
_sent -= (toSend - sent);
_ack -= (toSend - sent);
}
async_ws_log_v(
"SEND[%" PRIu8 "] => [%" PRIu16 "] WS_MSG_SENDING %u/%u (acked: %u/%u)", _opcode, client->remotePort(), _sent, _WSbuffer->size(), _acked, _ack
);
return sent;
}
/*
* Async WebSocket Client
*/
const char *AWSC_PING_PAYLOAD = "ESPAsyncWebServer-PING";
const size_t AWSC_PING_PAYLOAD_LEN = 22;
AsyncWebSocketClient::AsyncWebSocketClient(AsyncClient *client, AsyncWebSocket *server)
: _client(client), _server(server), _clientId(_server->_getNextId()), _status(WS_CONNECTED), _pstate(STATE_FRAME_START), _lastMessageTime(millis()),
_keepAlivePeriod(0), _tempObject(NULL) {
_client->setRxTimeout(0);
_client->onError(
[](void *r, AsyncClient *c, int8_t error) {
(void)c;
((AsyncWebSocketClient *)(r))->_onError(error);
},
this
);
_client->onAck(
[](void *r, AsyncClient *c, size_t len, uint32_t time) {
(void)c;
((AsyncWebSocketClient *)(r))->_onAck(len, time);
},
this
);
_client->onDisconnect(
[](void *r, AsyncClient *c) {
((AsyncWebSocketClient *)(r))->_onDisconnect();
delete c;
},
this
);
_client->onTimeout(
[](void *r, AsyncClient *c, uint32_t time) {
(void)c;
((AsyncWebSocketClient *)(r))->_onTimeout(time);
},
this
);
_client->onData(
[](void *r, AsyncClient *c, void *buf, size_t len) {
(void)c;
((AsyncWebSocketClient *)(r))->_onData(buf, len);
},
this
);
_client->onPoll(
[](void *r, AsyncClient *c) {
(void)c;
((AsyncWebSocketClient *)(r))->_onPoll();
},
this
);
memset(&_pinfo, 0, sizeof(_pinfo));
}
AsyncWebSocketClient::~AsyncWebSocketClient() {
{
#ifdef ESP32
std::lock_guard<std::recursive_mutex> lock(_lock);
#endif
_messageQueue.clear();
_controlQueue.clear();
}
_server->_handleEvent(this, WS_EVT_DISCONNECT, NULL, NULL, 0);
}
void AsyncWebSocketClient::_clearQueue() {
while (!_messageQueue.empty() && _messageQueue.front().finished()) {
_messageQueue.pop_front();
}
}
void AsyncWebSocketClient::_onAck(size_t len, uint32_t time) {
_lastMessageTime = millis();
#ifdef ESP32
std::unique_lock<std::recursive_mutex> lock(_lock);
#endif
async_ws_log_v("[%s][%" PRIu32 "] START ACK(%u, %" PRIu32 ") Q:%u", _server->url(), _clientId, len, time, _messageQueue.size());
if (!_controlQueue.empty()) {
auto &head = _controlQueue.front();
if (head.finished()) {
len -= head.len();
if (_status == WS_DISCONNECTING && head.opcode() == WS_DISCONNECT) {
_controlQueue.pop_front();
_status = WS_DISCONNECTED;
async_ws_log_v("[%s][%" PRIu32 "] ACK WS_DISCONNECTED", _server->url(), _clientId);
if (_client) {
#ifdef ESP32
/*
Unlocking has to be called before return execution otherwise std::unique_lock ::~unique_lock() will get an exception pthread_mutex_unlock.
Due to _client->close() shall call the callback function _onDisconnect()
The calling flow _onDisconnect() --> _handleDisconnect() --> ~AsyncWebSocketClient()
*/
lock.unlock();
#endif
_client->close();
}
return;
}
_controlQueue.pop_front();
}
}
if (len && !_messageQueue.empty()) {
for (auto &msg : _messageQueue) {
len = msg.ack(len, time);
if (len == 0) {
break;
}
}
}
_clearQueue();
async_ws_log_v("[%s][%" PRIu32 "] END ACK(%u, %" PRIu32 ") Q:%u", _server->url(), _clientId, len, time, _messageQueue.size());
_runQueue();
}
void AsyncWebSocketClient::_onPoll() {
if (!_client) {
return;
}
#ifdef ESP32
std::unique_lock<std::recursive_mutex> lock(_lock);
#endif
if (_client && _client->canSend() && (!_controlQueue.empty() || !_messageQueue.empty())) {
_runQueue();
} else if (_keepAlivePeriod > 0 && (millis() - _lastMessageTime) >= _keepAlivePeriod && (_controlQueue.empty() && _messageQueue.empty())) {
#ifdef ESP32
lock.unlock();
#endif
ping((uint8_t *)AWSC_PING_PAYLOAD, AWSC_PING_PAYLOAD_LEN);
}
}
void AsyncWebSocketClient::_runQueue() {
// all calls to this method MUST be protected by a mutex lock!
if (!_client) {
return;
}
_clearQueue();
size_t space = webSocketSendFrameWindow(_client);
if (space) {
// control frames have priority over message frames
// we can send a control frame if:
// - there is no message frame in the queue, or the first message frame is between frames (all bytes sent are acked)
// - the control frame is not finished (not sent yet)
// - there is enough space to send the control frame (control frames are small, at most 129 bytes, so we can assume that if there is space to send it, it can be sent in one go)
if (_messageQueue.empty() || _messageQueue.front().betweenFrames()) {
for (auto &ctrl : _controlQueue) {
if (ctrl.finished()) {
continue;
}
if (space > (size_t)(ctrl.len() - 1)) {
async_ws_log_v("[%s][%" PRIu32 "] SEND CTRL %" PRIu8, _server->url(), _clientId, ctrl.opcode());
ctrl.send(_client);
space = webSocketSendFrameWindow(_client);
}
}
}
// then we can send message frames if there is space
if (space) {
for (auto &msg : _messageQueue) {
if (msg._remainingBytesToSend()) {
async_ws_log_v(
"[%s][%" PRIu32 "][%" PRIu8 "] SEND %u/%u (acked: %u/%u)", _server->url(), _clientId, msg._opcode, msg._sent, msg._WSbuffer->size(), msg._acked,
msg._ack
);
// will use all the remaining space, or all the remaining bytes to send, whichever is smaller
msg.send(_client);
space = webSocketSendFrameWindow(_client);
// If we haven't finished sending this message, we must stop here to preserve WebSocket ordering.
// We can only pipeline subsequent messages if the current one is fully passed to TCP buffer.
if (msg._remainingBytesToSend()) {
async_ws_log_v("[%s][%" PRIu32 "][%" PRIu8 "] NO_SPACE", _server->url(), _clientId, msg._opcode);
break;
}
} else if (!space) {
// not enough space for another message
async_ws_log_v("[%s][%" PRIu32 "] NO_SPACE", _server->url(), _clientId);
break;
}
}
}
}
}
bool AsyncWebSocketClient::queueIsFull() const {
#ifdef ESP32
std::lock_guard<std::recursive_mutex> lock(_lock);
#endif
return (_messageQueue.size() >= WS_MAX_QUEUED_MESSAGES) || (_status != WS_CONNECTED);
}
size_t AsyncWebSocketClient::queueLen() const {
#ifdef ESP32
std::lock_guard<std::recursive_mutex> lock(_lock);
#endif
return _messageQueue.size();
}
bool AsyncWebSocketClient::canSend() const {
#ifdef ESP32
std::lock_guard<std::recursive_mutex> lock(_lock);
#endif
return _messageQueue.size() < WS_MAX_QUEUED_MESSAGES;
}
bool AsyncWebSocketClient::_queueControl(uint8_t opcode, const uint8_t *data, size_t len, bool mask) {
if (!_client) {
return false;
}
#ifdef ESP32
std::lock_guard<std::recursive_mutex> lock(_lock);
#endif
_controlQueue.emplace_back(opcode, data, len, mask);
async_ws_log_v("[%s][%" PRIu32 "] QUEUE CTRL (%u) << %" PRIu8, _server->url(), _clientId, _controlQueue.size(), opcode);
if (_client && _client->canSend()) {
_runQueue();
}
return true;
}
bool AsyncWebSocketClient::_queueMessage(AsyncWebSocketSharedBuffer buffer, uint8_t opcode, bool mask) {
if (!_client || buffer->size() == 0 || _status != WS_CONNECTED) {
return false;
}
#ifdef ESP32
std::unique_lock<std::recursive_mutex> lock(_lock);
#endif
if (_messageQueue.size() >= WS_MAX_QUEUED_MESSAGES) {
if (closeWhenFull) {
_status = WS_DISCONNECTED;
if (_client) {
#ifdef ESP32
/*
Unlocking has to be called before return execution otherwise std::unique_lock ::~unique_lock() will get an exception pthread_mutex_unlock.
Due to _client->close() shall call the callback function _onDisconnect()
The calling flow _onDisconnect() --> _handleDisconnect() --> ~AsyncWebSocketClient()
*/
lock.unlock();
#endif
_client->close();
}
async_ws_log_w("[%s][%" PRIu32 "] Too many messages queued: closing connection", _server->url(), _clientId);
} else {
async_ws_log_w("[%s][%" PRIu32 "] Too many messages queued: discarding new message", _server->url(), _clientId);
}
return false;
}
_messageQueue.emplace_back(buffer, opcode, mask);
async_ws_log_v("[%s][%" PRIu32 "] QUEUE MSG (%u/%u) << %" PRIu8, _server->url(), _clientId, _messageQueue.size(), WS_MAX_QUEUED_MESSAGES, opcode);
if (_client && _client->canSend()) {
_runQueue();
}
return true;
}
void AsyncWebSocketClient::close(uint16_t code, const char *message) {
if (_status != WS_CONNECTED) {
return;
}
async_ws_log_w("[%s][%" PRIu32 "] CLOSE", _server->url(), _clientId);
_status = WS_DISCONNECTING;
if (code) {
uint8_t packetLen = 2;
if (message != NULL) {
size_t mlen = strlen(message);
if (mlen > 123) {
mlen = 123;
}
packetLen += mlen;
}
char *buf = (char *)malloc(packetLen);
if (buf != NULL) {
buf[0] = (uint8_t)(code >> 8);
buf[1] = (uint8_t)(code & 0xFF);
if (message != NULL) {
memcpy(buf + 2, message, packetLen - 2);
}
_queueControl(WS_DISCONNECT, (uint8_t *)buf, packetLen);
free(buf);
return;
} else {
async_ws_log_e("Failed to allocate");
_client->abort();
}
}
_queueControl(WS_DISCONNECT);
}
bool AsyncWebSocketClient::ping(const uint8_t *data, size_t len) {
return _status == WS_CONNECTED && _queueControl(WS_PING, data, len);
}
void AsyncWebSocketClient::_onError(int8_t err) {
async_ws_log_v("[%s][%" PRIu32 "] ERROR %" PRIi8, _server->url(), _clientId, static_cast<int8_t>(err));
}
void AsyncWebSocketClient::_onTimeout(uint32_t time) {
if (!_client) {
return;
}
async_ws_log_v("[%s][%" PRIu32 "] TIMEOUT %" PRIu32, _server->url(), _clientId, time);
_client->close();
}
void AsyncWebSocketClient::_onDisconnect() {
async_ws_log_v("[%s][%" PRIu32 "] DISCONNECT", _server->url(), _clientId);
_client = nullptr;
_server->_handleDisconnect(this);
}
void AsyncWebSocketClient::_onData(void *pbuf, size_t plen) {
_lastMessageTime = millis();
uint8_t *data = (uint8_t *)pbuf;
while (plen > 0) {
async_ws_log_v(
"[%s][%" PRIu32 "] DATA plen: %" PRIu32 ", _pstate: %" PRIu8 ", _status: %" PRIu8, _server->url(), _clientId, plen, _pstate, static_cast<uint8_t>(_status)
);
if (_pstate == STATE_FRAME_START) {
const uint8_t *fdata = data;
_pinfo.index = 0;
_pinfo.final = (fdata[0] & 0x80) != 0;
_pinfo.opcode = fdata[0] & 0x0F;
_pinfo.masked = ((fdata[1] & 0x80) != 0) ? 1 : 0;
_pinfo.len = fdata[1] & 0x7F;
data += 2;
plen -= 2;
if (_pinfo.len == 126 && plen >= 2) {
_pinfo.len = fdata[3] | (uint16_t)(fdata[2]) << 8;
data += 2;
plen -= 2;
} else if (_pinfo.len == 127 && plen >= 8) {
_pinfo.len = fdata[9] | (uint16_t)(fdata[8]) << 8 | (uint32_t)(fdata[7]) << 16 | (uint32_t)(fdata[6]) << 24 | (uint64_t)(fdata[5]) << 32
| (uint64_t)(fdata[4]) << 40 | (uint64_t)(fdata[3]) << 48 | (uint64_t)(fdata[2]) << 56;
data += 8;
plen -= 8;
}
}
async_ws_log_v(
"[%s][%" PRIu32 "] DATA _pinfo: index: %" PRIu64 ", final: %" PRIu8 ", opcode: %" PRIu8 ", masked: %" PRIu8 ", len: %" PRIu64, _server->url(), _clientId,
_pinfo.index, _pinfo.final, _pinfo.opcode, _pinfo.masked, _pinfo.len
);
// Handle fragmented mask data - Safari may split the 4-byte mask across multiple packets
// _pinfo.masked is 1 if we need to start reading mask bytes
// _pinfo.masked is 2, 3, or 4 if we have partially read the mask
// _pinfo.masked is 5 if the mask is complete
while (_pinfo.masked && _pstate <= STATE_FRAME_MASK && _pinfo.masked < 5) {
// check if we have some data
if (plen == 0) {
// Safari close frame edge case: masked bit set but no mask data
if (_pinfo.opcode == WS_DISCONNECT) {
async_ws_log_v("[%s][%" PRIu32 "] DATA close frame with incomplete mask, treating as unmasked", _server->url(), _clientId);
_pinfo.masked = 0;
_pinfo.index = 0;
_pinfo.len = 0;
_pstate = STATE_FRAME_START;
break;
}
// wait for more data
_pstate = STATE_FRAME_MASK;
async_ws_log_v("[%s][%" PRIu32 "] DATA waiting for more mask data: read: %" PRIu8 "/4", _server->url(), _clientId, _pinfo.masked - 1);
return;
}
// accumulate mask bytes
_pinfo.mask[_pinfo.masked - 1] = data[0];
data += 1;
plen -= 1;
_pinfo.masked++;
}
// all mask bytes read if we were reading them
_pstate = STATE_FRAME_DATA;
// restore masked to 1 for backward compatibility
if (_pinfo.masked >= 5) {
async_ws_log_v("[%s][%" PRIu32 "] DATA mask read complete", _server->url(), _clientId);
_pinfo.masked = 1;
}
const size_t datalen = std::min((size_t)(_pinfo.len - _pinfo.index), plen);
if (_pinfo.masked) {
for (size_t i = 0; i < datalen; i++) {
data[i] ^= _pinfo.mask[(_pinfo.index + i) % 4];
}
}
if (_pinfo.index == 0) { // first fragment of the frame
// init message_opcode for this frame
// note: For next WS_CONTINUATION frames, they have opcode 0, so message_opcode will stay like the first frame
if (_pinfo.opcode == WS_TEXT || _pinfo.opcode == WS_BINARY) {
_pinfo.message_opcode = _pinfo.opcode;
}
// init frame number to 0 if only 1 frame or if this is the first frame of a fragmented message
if (_pinfo.final || datalen < _pinfo.len) {
_pinfo.num = 0;
}
}
if ((datalen + _pinfo.index) < _pinfo.len) { // more fragments to read for this frame
_pstate = STATE_FRAME_DATA;
if (datalen > 0) {
async_ws_log_v(
"[%s][%" PRIu32 "] DATA processing next fragment of %s frame %" PRIu32 ", index: %" PRIu64 ", len: %" PRIu32 "", _server->url(), _clientId,
(_pinfo.message_opcode == WS_TEXT) ? "text" : "binary", _pinfo.num, _pinfo.index, (uint32_t)datalen
);
_handleDataEvent(data, datalen, datalen == plen); // datalen == plen means that we are processing the last part of the current TCP packet
}
// track index for next fragment
_pinfo.index += datalen;
} else if ((datalen + _pinfo.index) == _pinfo.len) { // this is the last fragment for this frame
_pstate = STATE_FRAME_START;
if (_pinfo.opcode == WS_DISCONNECT) {
async_ws_log_v("[%s][%" PRIu32 "] DATA WS_DISCONNECT", _server->url(), _clientId);
if (datalen) {
uint16_t reasonCode = (uint16_t)(data[0] << 8) + data[1];
char *reasonString = (char *)(data + 2);
if (reasonCode > 1001) {
_server->_handleEvent(this, WS_EVT_ERROR, (void *)&reasonCode, (uint8_t *)reasonString, strlen(reasonString));
}
}
if (_status == WS_DISCONNECTING) {
_status = WS_DISCONNECTED;
if (_client) {
_client->close();
}
} else {
_status = WS_DISCONNECTING;
if (_client) {
_client->ackLater();
}
_queueControl(WS_DISCONNECT, data, datalen);
}
} else if (_pinfo.opcode == WS_PING) {
async_ws_log_v("[%s][%" PRIu32 "] DATA PING", _server->url(), _clientId);
_server->_handleEvent(this, WS_EVT_PING, NULL, NULL, 0);
_queueControl(WS_PONG, data, datalen);
} else if (_pinfo.opcode == WS_PONG) {
async_ws_log_v("[%s][%" PRIu32 "] DATA PONG", _server->url(), _clientId);
if (datalen != AWSC_PING_PAYLOAD_LEN || memcmp(AWSC_PING_PAYLOAD, data, AWSC_PING_PAYLOAD_LEN) != 0) {
_server->_handleEvent(this, WS_EVT_PONG, NULL, NULL, 0);
}
} else if (_pinfo.opcode < WS_DISCONNECT) { // continuation or text/binary frame
async_ws_log_v(
"[%s][%" PRIu32 "] DATA processing final fragment of %s frame %" PRIu32 ", index: %" PRIu64 ", len: %" PRIu32 "", _server->url(), _clientId,
(_pinfo.message_opcode == WS_TEXT) ? "text" : "binary", _pinfo.num, _pinfo.index, (uint32_t)datalen
);
_handleDataEvent(data, datalen, datalen == plen); // datalen == plen means that we are processing the last part of the current TCP packet
if (_pinfo.final) {
_pinfo.num = 0;
} else {
_pinfo.num += 1;
}
}
} else {
// unexpected frame error, close connection
_pstate = STATE_FRAME_START;
async_ws_log_v(
"[%s][%" PRIu32 "] DATA frame error: len: %u, index: %" PRIu64 ", total: %" PRIu64 "\n", _server->url(), _clientId, datalen, _pinfo.index, _pinfo.len
);
_status = WS_DISCONNECTING;
if (_client) {
_client->ackLater();
}
_queueControl(WS_DISCONNECT, data, datalen);
break;
}
data += datalen;
plen -= datalen;
}
}
void AsyncWebSocketClient::_handleDataEvent(uint8_t *data, size_t len, bool endOfPaquet) {
// ------------------------------------------------------------
// Issue 384: https://github.com/ESP32Async/ESPAsyncWebServer/issues/384
// Discussion: https://github.com/ESP32Async/ESPAsyncWebServer/pull/383#discussion_r2760425739
// The initial design of the library was doing a backup of the byte following the data buffer because the client code
// was allowed and documented to do something like data[len] = 0; to facilitate null-terminated string handling.
// This was a bit hacky but it was working and it was documented, although completely incorrect because it was modifying a byte outside of the data buffer.
// So to fix this behavior and to avoid breaking existing client code that may be relying on this behavior, we now have to copy the data to a temporary buffer that has an extra byte for the null terminator.
// ------------------------------------------------------------
//
// Optimization notes:
//
// 1) opcodes
//
// - info->opcode stores the current WS frame type (binary, text, continuation)
// - info->message_opcode stores the WS frame type of the first frame of the message, which is used for fragmented messages to know the message type when processing subsequent frame with opcode 0 (continuation)
// So we can use info->message_opcode to avoid copying the data for non-text frames, and only copy the data for text frames when we need to add a null terminator for client code convenience.
//
// 2) data copy vs data backup/restore
// - endOfPaquet: is true when datalen == plen. plen is the remaining bytes in the current TCP packet, so if datalen == plen, it means that we are processing the last part of the current TCP packet.
// In that case, we have to copy since we cannot backup/restore the byte after the data buffer.
// Otherwise we can backup the byte and restore since we know that the byte after is owned by the current TCP packet (same pointer).
if (_pinfo.message_opcode == WS_TEXT) {
if (endOfPaquet) {
std::unique_ptr<uint8_t[]> copy(new (std::nothrow) uint8_t[len + 1]());
if (copy) {
memcpy(copy.get(), data, len);
copy[len] = 0;
_server->_handleEvent(this, WS_EVT_DATA, (void *)&_pinfo, copy.get(), len);
} else {
async_ws_log_e("Failed to allocate");
if (_client) {
_client->abort();
}
}
} else {
uint8_t backup = data[len];
data[len] = 0;
_server->_handleEvent(this, WS_EVT_DATA, (void *)&_pinfo, data, len);
data[len] = backup;
}
} else {
_server->_handleEvent(this, WS_EVT_DATA, (void *)&_pinfo, data, len);
}
}
size_t AsyncWebSocketClient::printf(const char *format, ...) {
va_list arg;
va_start(arg, format);
size_t len = vsnprintf(nullptr, 0, format, arg);
va_end(arg);
if (len == 0) {
return 0;
}
char *buffer = new char[len + 1];
if (!buffer) {
return 0;
}
va_start(arg, format);
len = vsnprintf(buffer, len + 1, format, arg);
va_end(arg);
bool enqueued = text(buffer, len);
delete[] buffer;
return enqueued ? len : 0;
}
#ifdef ESP8266
size_t AsyncWebSocketClient::printf_P(PGM_P formatP, ...) {
va_list arg;
va_start(arg, formatP);
size_t len = vsnprintf_P(nullptr, 0, formatP, arg);
va_end(arg);
if (len == 0) {
return 0;
}
char *buffer = new char[len + 1];
if (!buffer) {
return 0;
}
va_start(arg, formatP);
len = vsnprintf_P(buffer, len + 1, formatP, arg);
va_end(arg);
bool enqueued = text(buffer, len);
delete[] buffer;
return enqueued ? len : 0;
}
#endif
namespace {
AsyncWebSocketSharedBuffer makeSharedBuffer(const uint8_t *message, size_t len) {
auto buffer = std::make_shared<std::vector<uint8_t>>(len);
std::memcpy(buffer->data(), message, len);
return buffer;
}
} // namespace
bool AsyncWebSocketClient::text(AsyncWebSocketMessageBuffer *buffer) {
bool enqueued = false;
if (buffer) {
enqueued = text(std::move(buffer->_buffer));
delete buffer;
}
return enqueued;
}
bool AsyncWebSocketClient::text(AsyncWebSocketSharedBuffer buffer) {
return _queueMessage(buffer);
}
bool AsyncWebSocketClient::text(const uint8_t *message, size_t len) {
return text(makeSharedBuffer(message, len));
}
bool AsyncWebSocketClient::text(const char *message, size_t len) {
return text((const uint8_t *)message, len);
}
bool AsyncWebSocketClient::text(const char *message) {
return text(message, strlen(message));
}
bool AsyncWebSocketClient::text(const String &message) {
return text(message.c_str(), message.length());
}
#ifdef ESP8266
bool AsyncWebSocketClient::text(const __FlashStringHelper *data) {
PGM_P p = reinterpret_cast<PGM_P>(data);
size_t n = 0;
while (1) {
if (pgm_read_byte(p + n) == 0) {
break;
}
n += 1;
}
char *message = (char *)malloc(n + 1);
bool enqueued = false;
if (message) {
memcpy_P(message, p, n);
message[n] = 0;
enqueued = text(message, n);
free(message);
}
return enqueued;
}
#endif // ESP8266
bool AsyncWebSocketClient::binary(AsyncWebSocketMessageBuffer *buffer) {
bool enqueued = false;
if (buffer) {
enqueued = binary(std::move(buffer->_buffer));
delete buffer;
}
return enqueued;
}
bool AsyncWebSocketClient::binary(AsyncWebSocketSharedBuffer buffer) {
return _queueMessage(buffer, WS_BINARY);
}
bool AsyncWebSocketClient::binary(const uint8_t *message, size_t len) {
return binary(makeSharedBuffer(message, len));
}
bool AsyncWebSocketClient::binary(const char *message, size_t len) {
return binary((const uint8_t *)message, len);
}
bool AsyncWebSocketClient::binary(const char *message) {
return binary(message, strlen(message));
}
bool AsyncWebSocketClient::binary(const String &message) {
return binary(message.c_str(), message.length());
}
#ifdef ESP8266
bool AsyncWebSocketClient::binary(const __FlashStringHelper *data, size_t len) {
PGM_P p = reinterpret_cast<PGM_P>(data);
char *message = (char *)malloc(len);
bool enqueued = false;
if (message) {
memcpy_P(message, p, len);
enqueued = binary(message, len);
free(message);
}
return enqueued;
}
#endif
IPAddress AsyncWebSocketClient::remoteIP() const {
if (!_client) {
return IPAddress((uint32_t)0U);
}
return _client->remoteIP();
}
uint16_t AsyncWebSocketClient::remotePort() const {
if (!_client) {
return 0;
}
return _client->remotePort();
}
/*
* Async Web Socket - Each separate socket location
*/
void AsyncWebSocket::_handleEvent(AsyncWebSocketClient *client, AwsEventType type, void *arg, uint8_t *data, size_t len) {
if (_eventHandler != NULL) {
_eventHandler(this, client, type, arg, data, len);
}
}
AsyncWebSocketClient *AsyncWebSocket::_newClient(AsyncWebServerRequest *request) {
#ifdef ESP32
std::lock_guard<std::recursive_mutex> lock(_lock);
#endif
_clients.emplace_back(request, this);
// we've just detached AsyncTCP client from AsyncWebServerRequest
_handleEvent(&_clients.back(), WS_EVT_CONNECT, request, NULL, 0);
// after user code completed CONNECT event callback we can delete req/response objects
delete request;
return &_clients.back();
}