-
Notifications
You must be signed in to change notification settings - Fork 5
/
WebSocket.cpp
1324 lines (1224 loc) · 63.5 KB
/
WebSocket.cpp
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
863
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
//
// WebSocket - A lightweight RFC 6455 (Web Socket) implementation for Qt5
// Copyright (C) 2019-2020 Calin A. Culianu <[email protected]>
//
// The MIT License (MIT)
//
// 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.#pragma once
//
#include "WebSocket.h"
#include <QCryptographicHash>
#include <QDateTime>
#include <QHash>
#include <QHostAddress>
#include <QList>
#include <QLocale>
#include <QMetaObject>
#include <QRandomGenerator>
#include <QSet>
#include <QSslSocket>
#include <QTcpSocket>
#include <QtDebug>
#include <QtEndian>
#include <QTimer>
#include <QUrl>
#include <algorithm>
#include <cassert>
#include <cstddef>
#include <chrono>
#include <cstring>
#include <limits>
#include <memory>
#if defined(Q_OS_WINDOWS)
#define WIN32_LEAN_AND_MEAN 1
#define NOMINMAX
# include <windows.h>
#endif
#ifdef __clang__
// turn off the dreaded "warning: class padded with xx bytes, etc" since we aren't writing wire protocols using structs..
#pragma clang diagnostic ignored "-Wpadded"
#endif
namespace WebSocket
{
Exception::Exception(const QString &s) : std::runtime_error(s.toUtf8().constData()) {}
Exception::~Exception() {} // for vtable
BadArgs::~BadArgs() {} // for vtable
InternalError::~InternalError() {} // for vtable
Error::~Error() {} // for vtable
MessageTooBigError::~MessageTooBigError() {} // for vtable
namespace {
#ifndef Q_OS_WINDOWS
const auto _t0 = std::chrono::high_resolution_clock::now();
/// Returns the absolute time in milliseconds since program start. Uses an accurate monotic clock.
inline qint64 getTime() {
const auto now = std::chrono::high_resolution_clock::now();
return std::chrono::duration_cast<std::chrono::milliseconds>(now - _t0).count();
}
#else // Windows -- doesn't always have an accurate or supported std::chrono::high_resolution_clock, so we do platform-specific calls directly.
std::int64_t _getAbsTimeNS()
{
static __int64 freq = 0;
__int64 ct, factor;
if (!freq) {
QueryPerformanceFrequency((LARGE_INTEGER *)&freq);
}
QueryPerformanceCounter((LARGE_INTEGER *)&ct); // reads the current time (in system units)
factor = 1000000000LL/freq;
if (factor <= 0) factor = 1;
return std::int64_t(ct * factor);
}
const auto _t0 = _getAbsTimeNS();
/// Returns the absolute time in milliseconds since program start. Uses an accurate monotic clock.
inline qint64 getTime() {
return (_getAbsTimeNS() - _t0) / 1000000LL;
}
#endif
namespace Compat {
inline constexpr auto SplitBehaviorSkipEmptyParts =
#if QT_VERSION >= QT_VERSION_CHECK(5,15,0)
Qt::SkipEmptyParts;
#else
QString::SkipEmptyParts;
#endif
inline constexpr auto SplitBehaviorKeepEmptyParts [[maybe_unused]] =
#if QT_VERSION >= QT_VERSION_CHECK(5,15,0)
Qt::KeepEmptyParts;
#else
QString::KeepEmptyParts;
#endif
template <class SocketClass = QAbstractSocket>
inline constexpr auto SocketErrorSignalFunctionPtr() noexcept {
#if QT_VERSION >= QT_VERSION_CHECK(5, 15, 0)
return &SocketClass::errorOccurred;
#else
return qOverload<QAbstractSocket::SocketError>(&SocketClass::error); // Deprecated in Qt 5.15
#endif
}
} // namespace Compat
} // namespace
using Byte = quint8;
QString frameTypeName(FrameType ft)
{
switch(ft) {
case FrameType::Text: return QStringLiteral("Text");
case FrameType::Binary: return QStringLiteral("Binary");
case FrameType::Ctl_Ping: return QStringLiteral("Ping");
case FrameType::Ctl_Pong: return QStringLiteral("Pong");
case FrameType::Ctl_Close: return QStringLiteral("Close");
case FrameType::_Continuation: return QStringLiteral("Continuation");
}
return QStringLiteral("Unknown (0x%1)").arg(quint8(ft), 2, 16, QChar('0'));
}
namespace Ser {
QByteArray wrapPayload(const QByteArray &data, FrameType type, bool isMasked, std::size_t fragmentSize)
{
const bool isCtl = type & 0x08;
if (isCtl)
fragmentSize = 125; // force 125 for below code to work
// see: https://tools.ietf.org/html/rfc6455#section-5.2
if (fragmentSize == 0)
throw BadArgs("fragmentSize may not be 0");
if (fragmentSize > std::uint64_t(std::numeric_limits<std::int64_t>::max()))
throw BadArgs("fragmentSize cannot exceed a 63-bit size");
if (isCtl && data.size() > 125)
throw BadArgs("control frames may not exceed 125 bytes of payload data");
const auto dsize = std::size_t(data.size());
constexpr int maxUShort = std::numeric_limits<std::uint16_t>::max();
fragmentSize = std::max(std::min(dsize, fragmentSize), std::size_t(1));
const auto nFragments = std::max(std::size_t(1), std::size_t((dsize / fragmentSize) (fragmentSize > 1UL && dsize % fragmentSize ? 1UL : 0UL)));
const auto perFragmentOverhead =
2UL // base opcode byte minimum payload length byte
(isMasked ? 4UL : 0) // if we have a mask, then the mask is encoded in the frame, per-frame as 4 bytes
(fragmentSize > 125UL // sizes > 125 bytes are either 2-byte or 8-byte
? (fragmentSize <= std::size_t(maxUShort) // does it fit in 2 bytes? (65535)
? 2UL // yes, it's <= 65535 and >= 126
: 8UL) // no, it does not, use a 64-bit (actually 63-bit size)
: 0UL); // <= 125 byte frame, no extra length bytes needed
const auto retSize = dsize perFragmentOverhead * nFragments;
if (retSize > std::numeric_limits<int>::max())
throw MessageTooBigError(QString("resulting buffer size of %1 is too large").arg(retSize));
QByteArray ret(int(retSize), Qt::Uninitialized); // the last fragment here may contain too much data (at most 8 extra bytes)
int nBytesRemain = int(dsize);
Byte *dest = reinterpret_cast<Byte *>(ret.data());
const Byte *src = reinterpret_cast<const Byte *>(data.constData());
Byte opcode = Byte(type); // we intentionally made the enum type match the opcodes defined in the RFC
const Byte maskBit = isMasked ? 0x80 : 0x0;
assert(nFragments == 1 || type == Text || type == Binary);
for (std::size_t i = 0; i < nFragments; i) {
const quint32 mask = isMasked ? QRandomGenerator::global()->generate() : 0U;
const Byte *pmask = reinterpret_cast<const Byte *>(isMasked ? &mask : nullptr);
// write opcode byte
*dest = Byte( opcode
// FIN-bit is the MSB bit. It is set if this is the last (or only) frame
| (i == nFragments-1 ? 0x80 : 0x0) );
const int bytes2write = std::min(nBytesRemain, int(fragmentSize));
// write length byte(s)
if (bytes2write <= 125)
*dest = Byte(bytes2write) | maskBit;
else if (bytes2write <= maxUShort) {
// >= 126, <= 65535
*dest = Byte(126) | maskBit; // indicate extended payload (2 bytes)
qToBigEndian(quint16(bytes2write), dest);
dest = 2;
} else {
// >= 65536
*dest = Byte(127) | maskBit; // indicate extended payload (8 bytes)
qToBigEndian(quint64(bytes2write), dest);
dest = 8;
}
if (pmask == nullptr) {
assert(!maskBit);
// no mask, just write the frame data directly
std::memcpy(dest, src, std::size_t(bytes2write));
// update positions
dest = bytes2write;
src = bytes2write;
} else {
assert(maskBit);
// mask is set -- write the octets xor'd with the mask
// first: write the 4 mask bytes themselves to the header so that the other end can decode
std::memcpy(dest, pmask, 4);
dest = 4;
// next: write the payload xor'd with the mask bytes
for (int j = 0; j < bytes2write; j)
*dest = *src ^ pmask[j % 4];
}
// update bytes remaining
nBytesRemain -= bytes2write;
// fragments after the first use opcode=0x0 (continuation frame)
opcode = FrameType::_Continuation;
}
const char * const endpos = reinterpret_cast<char *>(dest);
//#ifdef QT_DEBUG
// qDebug("Used %d/%d bytes", int(endpos-ret.constData()), ret.size());
//#endif
assert(endpos >= ret.constData() && endpos <= ret.constData() ret.size());
// truncate the QByteArray down to the actual number of bytes used
ret.truncate(int(endpos - ret.constData()));
return ret;
}
QByteArray makeCloseFrame(bool isMasked, CloseCode code, const QByteArray &reason)
{
QByteArray buf(2, Qt::Uninitialized);
qToBigEndian(quint16(code), buf.data());
if (!reason.isEmpty())
buf = reason.left(123);
return wrapPayload(buf, FrameType::Ctl_Close, isMasked);
}
} // end namspace Ser
namespace Deser {
ProtocolError::~ProtocolError() {} // for vtable
namespace {
inline constexpr auto kMessageTooBig1 = "invalid payload length (>INT_MAX!)";
inline void applyMask(Byte *buf, unsigned bufLen, const Byte *mask) {
for (unsigned i = 0; i < bufLen; i)
buf[i] = buf[i] ^ mask[i % 4];
}
struct PartialFrame : public Frame {
bool fin{}; // .fin is always true if .isControl() is true, but not the other way around
// these point to the source buffer
const Byte *begin = nullptr, *payloadBegin = nullptr, *end = nullptr;
const Byte *mask = nullptr; // pointer to mask in src buffer -- non-null only iff this->masked == true
bool accepted = false;
// helpers -- these refer to the source buffer
inline std::size_t srcWireLen() const { return end > begin ? std::size_t(end-begin) : 0U; }
inline std::size_t srcPayloadLen() const { return end > payloadBegin ? std::size_t(end-payloadBegin) : 0U; }
inline void loadDataFromSrc(QByteArray *dest) {
assert(dest);
if (payloadBegin) {
dest->reserve(std::max(dest->capacity(), dest->size() int(srcPayloadLen())));
dest->append(reinterpret_cast<const char *>(payloadBegin), int(srcPayloadLen()));
if (mask && masked)
applyMask(reinterpret_cast<Byte *>(dest->data() dest->length() - int(srcPayloadLen())),
unsigned(srcPayloadLen()), mask);
}
}
};
// Note the returned frames do NOT have the src data copied in! They all have .payload.isEmpty().
// Calling code should use loadDataFromSrc() later to load the frames if/when they are accepted
std::optional<PartialFrame> parseFrame(const Byte * const pos, const std::size_t len, MaskEnforcement maskEnforcement) {
std::optional<PartialFrame> ret;
if (len >= 2) {
std::size_t header = 2;
auto opByte = pos[0], lenByte = pos[1];
const bool isFin = opByte & 0x80; // highest bit indicates FIN
opByte = opByte & 0x0F; // take lower 4 bits (nibble)
const bool isMasked = lenByte & 0x80; // hightest bit indicates masked
lenByte = lenByte & 0x7F; // take lower 7 bits
// enforce mask, if maskEnforcement requires it
if (maskEnforcement == RequireMasked && !isMasked)
throw ProtocolError("encountered an unmasked frame, however masked frames are required");
else if (maskEnforcement == RequireUnmasked && isMasked)
throw ProtocolError("encountered a masked frame, however unmasked frames are required");
if (isMasked)
header = 4;
switch(opByte) {
case FrameType::Ctl_Ping:
case FrameType::Ctl_Pong:
case FrameType::Ctl_Close:
if (!isFin)
throw ProtocolError("fragmented control frame");
if (lenByte > 125)
throw ProtocolError("control frame has illegal size");
[[fallthrough]];
case FrameType::Text:
case FrameType::Binary:
case FrameType::_Continuation: // fragment continuation frame
{
constexpr auto kNonMinimalEncoding = "non-minimal length encoding encountered";
std::size_t parsedLen = lenByte;
if (lenByte == 126) {
header = 2;
if (len >= header) {
parsedLen = qFromBigEndian<quint16>(pos 2);
if (parsedLen < lenByte)
throw ProtocolError(kNonMinimalEncoding);
} else
break; // break out of switch, indicates not enough data is available
} else if (lenByte == 127) {
header = 8;
if (len >= header) {
parsedLen = qFromBigEndian<quint64>(pos 2);
if (parsedLen < lenByte)
throw ProtocolError(kNonMinimalEncoding);
if (parsedLen > quint64(std::numeric_limits<qint64>::max()))
// this indicates the actual other end is sending garbage
throw ProtocolError("invalid payload length (length cannot exceeded a 63-bit integer)");
if (parsedLen > quint64(std::numeric_limits<int>::max()))
// this indicates our implementation's limitation
throw MessageTooBigError(kMessageTooBig1);
} else
break; // break out of switch, indicates not enough data is available
}
const std::size_t total = header parsedLen;
if (len >= total) {
const Byte *mask = isMasked ? pos header - 4 : nullptr;
ret.emplace(
PartialFrame{
Frame{
FrameType(opByte),
isMasked,
{}, // .payload; never copy out payload data. Calling code will do this as needed.
},
isFin,
pos, // .begin
pos header, // .payloadBegin
pos total, // .end
mask // .mask
}
);
}
}
break;
default:
// unknown opcode byte
throw ProtocolError(QString("unknown frame opcode: 0x%1").arg(opByte, 2, 16, QChar('0')));
}
}
return ret;
}
}
std::list<Frame> parseBuffer(QByteArray &buf, MaskEnforcement maskEnforcement)
{
std::list<Frame> ret;
using PFList = std::list<PartialFrame>;
PFList allFrames;
std::list<PFList::iterator> ctlFrames, allDataFrames, acceptedDataFrames; // iterators pointing into "allFrames"
const Byte * d = reinterpret_cast<const Byte *>(buf.constData());
std::size_t len = std::size_t(buf.size()), pos = 0;
// cf_a df1_a df1_b cf_b df1_c df0_d df0_d df1_d cf_c df0_e df0_e -> cf_a cf_b cf_c df_a df_b df_c df_d [with df0_e left over]
while (auto optFrame = parseFrame(d pos, len - pos, maskEnforcement)) {
{
PartialFrame & pf = *optFrame;
pos = pf.srcWireLen();
allFrames.emplace_back( std::move(pf) );
}
auto back_it = allFrames.end();
--back_it;
if (back_it->isControl()) {
ctlFrames.push_back( back_it );
back_it->accepted = true; // mark accepted -- this is used below to know which data to keep in the buffer and which to discard because it was already copied
} else {
// queue the data frames for further analysis below
allDataFrames.push_back( back_it );
}
}
// Remember what the unparsed/leftover stuff at the end was because we need to keep that around as leftovers
const Byte * const keepAtEndBegin = d pos;
const int keepAtEndLen = int(len) - int(pos);
int keepReserveSize = keepAtEndLen;
// Now we have all the frames.
// Next, search through the dataFrames and figure out ranges that we accept,
// as well as predicate violations. We throw if:
// - we encounter 0x0 continue frames without a preceding start data frame
// - we encounter FIN frames that have non-zero opcode
// - we encounter fragment START frames that have a zero opcode
for (auto it = allDataFrames.begin(), end = allDataFrames.end(); it != end; it) {
PFList::iterator pfi = *it;
if (pfi->fin) {
if (pfi->type == FrameType::_Continuation)
throw ProtocolError("encountered a 'continue' frame with the FIN bit set, but without a corresponding start frame");
// non-fragmented FIN data frame, accept.
acceptedDataFrames.push_back(pfi);
} else {
// search for a range of frames that end in a "FIN" frame
std::list<PFList::iterator> maybes;
auto it2 = it;
int cumSize = 0;
for (; it2 != end; it2) {
maybes.push_back(*it2);
cumSize = int(maybes.back()->srcWireLen());
if (const auto type = (*it2)->type; it == it2) {
// make sure that first frame in fragment set has opcode != 0, as per the RFC
if (type == FrameType::_Continuation)
throw ProtocolError("encountered a fragment start frame with opcode set to 0");
} else {
// make sure that all subsequent fragments after the first have opcode == 0, as per the RFC
if (type != FrameType::_Continuation)
throw ProtocolError(QString("encountered a continue frame with non-zero opcode: 0x%1")
.arg(int(type), 2, 16, QChar('0')));
}
// we found a FIN frame, indicate this by breaking out of loop
if ((*it2)->fin)
break;
}
if (it2 != end) { // did we encounter a FIN frame?
// yes, accept all of the maybes
acceptedDataFrames.splice(acceptedDataFrames.end(), std::move(maybes) );
it = it2; // update our outer loop iterator to point past this range
} else {
// no, break out of outer loop since we know nothing good is after 'it'.
keepReserveSize = cumSize; // remember this cumulative size of stuff we didn't process for later: keepBuf.reserve()
break;
}
}
}
// now, copy out the PartialFrames -> ret Frame
// first, the control frames go in front
for (const auto & pfi : ctlFrames) {
ret.push_back( *pfi );
pfi->loadDataFromSrc(&ret.back().payload); // copy the data now directly to the destination Frame
}
// next the acceptable data frames, with fragments collapsed down into one destination Frame
std::optional<Frame> tmpFrame;
for (auto & pfi : acceptedDataFrames) {
pfi->accepted = true; // mark ALL accepted now
if (pfi->type == FrameType::Text || pfi->type == FrameType::Binary) {
tmpFrame = *pfi;
tmpFrame->payload.clear(); // this should already be empty, but to be defensive we must ensure data is empty initially
// data will be copied below
} else if (pfi->type == FrameType::_Continuation && tmpFrame) {
// data will be copied below
} else
// they sent us a continuation frame with a FIN set.. but with no corresponding start frame.
// note that this should not normally get triggered as we guard for it above already, but this
// was left in for defensive programming.
throw ProtocolError(QString("%1: Unexpected state in processing frame -- type=%2 tmpFrame=%3")
.arg(__func__).arg(pfi->type).arg(tmpFrame ? "valid" : "invalid"));
// guard against ridiculously big messages that exceed QByteArray size limits
if (std::size_t(tmpFrame->payload.length()) pfi->srcPayloadLen() > std::size_t(std::numeric_limits<int>::max()))
throw MessageTooBigError(kMessageTooBig1);
// append data to tmpFrame
pfi->loadDataFromSrc(&tmpFrame->payload);
if (pfi->fin) {
ret.emplace_back(std::move(*tmpFrame));
tmpFrame.reset();
}
}
if (tmpFrame)
// code above should guard against this -- this should never happen
throw InternalError(QString("%1: Unexpected state -- tmpFrame was not pushed back .. FIXME!").arg(__func__));
// finally, copy back pieces of data we didn't process so that the `buf` arg now only contains unprocessed data.
{
QByteArray keepBuf;
keepBuf.reserve(keepReserveSize);
//qDebug("Reserved: %d", keepReserveSize);
for (const auto & f : allFrames) {
if (f.accepted) // this data chunk was accepted, don't keep.
continue;
// data not accepted here, keep the unprocessed frames for next time
keepBuf.append(reinterpret_cast<const char *>(f.begin), int(f.srcWireLen()));
}
if (keepAtEndLen > 0)
keepBuf.append(reinterpret_cast<const char *>(keepAtEndBegin), keepAtEndLen);
else if (keepAtEndLen < 0)
// Defensive programming. This should never happen.
throw InternalError("keepAtEndLen < 0! FIXME!");
//qDebug("Actual: %d", keepBuf.size());
buf = keepBuf; // re-assign the buffer now
}
return ret;
}
CloseFrameInfo & CloseFrameInfo::operator=(const Frame &f)
{
if (f.payload.size() >= 2) {
code = qFromBigEndian<quint16>(f.payload.constData());
reason = f.payload.mid(2);
} else {
code.reset();
reason = f.payload; // single-byte reason. It's in-spec, I guess.
}
return *this;
}
} // end namespace Deser
namespace Handshake {
namespace {
/// UUID used for handshake from RFC 6455
const auto UUID = QByteArrayLiteral("258EAFA5-E914-47DA-95CA-C5AB0DC85B11");
/// some property keys -- these get written to the QTcpSocket
constexpr auto kHandshakeStartedFlag = "websocket-handshake-started-flag",
kWebsocketFlag = "websocket-protocol",
kWebsocketHeaders = "websocket-headers",
kWebsocketReqResource = "websocket-request-resource";
/// Some error templates used in ClientSide::start() and ServerSide::start()
constexpr auto kMaxHeadersExceeded = "maxHeaders exceeded",
kBadHttpLine = "Bad HTTP: %1";
const auto HttpMagic = QByteArrayLiteral("HTTP/");
// this function is a copy of QHttpNetworkReplyPrivate::parseStatus
bool parseStatusLine(const QByteArray &status, int *majorVersion, int *minorVersion,
int *statusCode, QString *reasonPhrase)
{
// from RFC 2616:
// Status-Line = HTTP-Version SP Status-Code SP Reason-Phrase CRLF
// HTTP-Version = "HTTP" "/" 1*DIGIT "." 1*DIGIT
// that makes: 'HTTP/n.n xxx Message'
// byte count: 0123456789012
constexpr int minLength = 11;
constexpr int dotPos = 6;
constexpr int spacePos = 8;
if (status.length() < minLength
|| !status.startsWith(HttpMagic)
|| status.at(dotPos) != '.'
|| status.at(spacePos) != ' ') {
// I don't know how to parse this status line
return false;
}
// optimize for the valid case: defer checking until the end
*majorVersion = status.at(dotPos - 1) - '0';
*minorVersion = status.at(dotPos 1) - '0';
int i = spacePos;
int j = status.indexOf(' ', i 1); // j == -1 || at(j) == ' ' so j 1 == 0 && j 1 <= length()
const QByteArray code = status.mid(i 1, j - i - 1);
bool ok;
*statusCode = code.toInt(&ok);
*reasonPhrase = QString::fromLatin1(status.constData() j 1);
return ok && uint(*majorVersion) <= 9 && uint(* minorVersion) <= 9;
}
bool parseReqLine(const QByteArray & line, int *majorVersion, int *minorVersion, QString *reqMethod, QString *reqResource)
{
// Request-Line = Method SP Request-URI SP HTTP-Version CRLF
// Method - all caps, one of: OPTIONS, GET, HEAD, POST, PUT, DELETE, TRACE, CONNECT
// Requiest-URI: 1 or more characters, URL encoded (no spaces)
// HTTP-Version = "HTTP" "/" 1*DIGIT "." 1*DIGIT
constexpr int minLength = 12, dotPos = 6;
static const QSet<QByteArray> acceptedMethods = {
"OPTIONS", "GET", "HEAD", "POST", "PUT", "DELETE", "TRACE", "CONNECT"
};
if (line.length() < minLength)
return false;
auto toks = line.split(' ');
if (toks.size() != 3)
return false;
auto tmp = toks[0].trimmed();
if (!acceptedMethods.contains(tmp))
return false;
*reqMethod = tmp;
tmp = toks[1].trimmed();
if (tmp.isEmpty())
return false;
*reqResource = QUrl::fromPercentEncoding(tmp);
tmp = toks[2].trimmed();
if (!tmp.startsWith(HttpMagic))
return false;
if (uint(*majorVersion = tmp.at(dotPos - 1) - '0') > 9)
return false;
if (uint(*minorVersion = tmp.at(dotPos 1) - '0') > 9)
return false;
return true;
}
}
namespace Async {
ClientServerBase::ClientServerBase(QTcpSocket *s)
: QObject(s), sock(s)
{
setObjectName(QStringLiteral("WebSocket::Handshake::Async::ClientServerBase"));
if (!sock) {
qWarning("ClientSide object constructed with a nullptr QTcpSocket");
}
connect(this, &ClientSide::success, this, &ClientSide::finished);
connect(this, &ClientSide::failure, this, [this]{
if (autodisconnect && sock) {
//qDebug("Auto-disconnecting");
sock->disconnectFromHost();
}
emit finished();
});
connect(this, &ClientSide::finished, this, [this]{
if (autodelete) deleteLater();
else if (sock) disconnect(sock, &QAbstractSocket::readyRead, this, nullptr);
//qDebug("finished");
});
}
ClientServerBase::~ClientServerBase() {} ///< for vtable
bool ClientServerBase::checkHeaders(QString *what) const
{
const auto Fail = [what](const QString &_what) {
if (what != nullptr)
*what = _what;
return false;
};
if (headers.isEmpty())
return Fail("Empty headers");
if (headers.value(QStringLiteral("upgrade")).toLower() != QStringLiteral("websocket"))
return Fail("Missing Upgrade: websocket header");
// Lastly, scan `Connection:` header items. We succeed if "upgrade" is found in the list. We only
// scan the first 64 header items in the connection header, e.g.: "Connection: item1, item2..".
constexpr int kMaxConnectionHeaderItems = 64;
const auto items = headers.value(QStringLiteral("connection")).split(',', Compat::SplitBehaviorSkipEmptyParts)
.mid(0, kMaxConnectionHeaderItems);
for (auto &str : items) {
if (str.trimmed().toLower() == QStringLiteral("upgrade"))
// found required Connection: upgrade item -- success!
return true;
}
// fail: no "upgrade" item found in the loop above
return Fail("Missing Connection: upgrade header");
} // end function ClientServerBase::checkHeaders
bool ClientServerBase::startCommon(int timeout)
{
if (!sock) {
emit failure("QTcpSocket is nullptr");
return false;
}
if (sock->state() != QAbstractSocket::SocketState::ConnectedState) {
emit failure("Socket is not connected");
return false;
}
if (!sock->property(kWebsocketFlag).isNull()) {
emit failure("Socket already negotiated protocol successfully");
return false;
}
if (!sock->property(kHandshakeStartedFlag).isNull()) {
emit failure("Already started once");
return false;
}
if (QSslSocket *ssl = dynamic_cast<QSslSocket *>(sock); ssl && !ssl->isEncrypted()) {
emit failure("SSL socket is not in encrypted mode");
return false;
}
if (!conns.isEmpty() || timer) {
// This should never happen. Added in the interests of defensive programming.
emit failure("INTERNAL ERROR: ConnList is not empty or timer is not nullptr (this should never happen)");
return false;
}
sock->setProperty(kHandshakeStartedFlag, true);
// cleanup func
conns = connect(this, &ClientSide::finished, this, [this]{
if (timer) {
timer->stop();
delete timer;
timer = nullptr;
}
for (auto & conn : conns)
QObject::disconnect(conn);
conns.clear();
});
// detect disconnect
conns = connect(sock, &QAbstractSocket::disconnected, this, [this]{
emit failure("Connection lost");
});
if (timeout > 0) {
if (timer) delete timer;
timer = new QTimer(this);
conns = connect(timer, &QTimer::timeout, this, [this]{
emit failure("Timed out");
});
timer->setSingleShot(true);
timer->start(timeout);
}
nread = 0;
headers.clear();
conns = connect(sock, &QAbstractSocket::readyRead, this, [this]{ on_ReadyRead(); });
return true;
} // end function ClientServerBase::startCommon
// --- ClientSide
ClientSide::~ClientSide() { /*qDebug("%s", __func__);*/ }
void ClientSide::start(const QString &resourceName, const QString &host, const QString &origin, int timeout)
{
if (!startCommon(timeout))
return;
// sock already had some bytes.. this shouldn't happen. Indicate failure.
if (sock->bytesAvailable()) {
emit failure("Other end sent us data unexpectedly");
return;
}
// generate key
QByteArray secKey(16, Qt::Uninitialized);
QRandomGenerator::global()->fillRange(reinterpret_cast<quint32 *>(secKey.data()),
unsigned(secKey.size()) / sizeof(quint32));
secKey = secKey.toBase64(); // encode the key now since we need it in this form for the SHA1
expectedDigest = QString::fromLatin1(QCryptographicHash::hash(secKey UUID, QCryptographicHash::Algorithm::Sha1).toBase64());
const auto originTrimmed = origin.trimmed();
// -- send header
const QByteArray header =
QStringLiteral(
"GET %1 HTTP/1.1\r\n"
"Host: %2\r\n"
"%3" // may be empty or may be "Origin: originargtext\r\n"
"Upgrade: websocket\r\n"
"Connection: Upgrade\r\n"
"Sec-WebSocket-Key: %4\r\n"
"Sec-WebSocket-Version: 13\r\n"
"\r\n"
).arg(resourceName.trimmed(),
host.trimmed(),
originTrimmed.isEmpty() ? QString() : QStringLiteral("Origin: %1\r\n").arg(originTrimmed),
QString::fromLatin1(secKey)).toLatin1();
//qDebug("Sending header:\n%s", header.constData());
sock->write(header);
} // end function ClientSide::start
void ClientSide::on_ReadyRead()
{
bool headersFinished = false;
bool expectingStatusLine = nread == 0;
try {
constexpr auto Fail = [](const QString &what) { throw Exception(what); };
while (sock->canReadLine()) {
if (maxHeaders > 0 && sock->bytesAvailable() > maxHeaders)
Fail(kMaxHeadersExceeded); // will implicitly disconnect signals from sock
auto line = sock->readLine();
nread = line.size();
if (maxHeaders > 0 && nread > maxHeaders)
Fail(kMaxHeadersExceeded);
line = line.trimmed();
if (line.isEmpty()) {
// end of headers
headersFinished = true;
break;
}
//qDebug("Got line: %s", line.constData());
if (expectingStatusLine) {
// parse status line
QString reasonPhrase;
int major, minor, code;
if (!parseStatusLine(line, &major, &minor, &code, &reasonPhrase)
|| major < 1 || minor < 1 || code != 101)
Fail(QString(kBadHttpLine).arg(QString(line)));
//qDebug("Got HTTP status 101 ok");
expectingStatusLine = false;
} else {
// expecting Header: value
const auto parts = line.split(':');
if (parts.size() < 2)
Fail("Bad header line");
const QString key = QString::fromLatin1(parts.front().trimmed().toLower()),
value = QString::fromLatin1(parts.mid(1).join(':').trimmed());
headers[key] = value;
//qDebug("[Added header: %s=%s]", key.toUtf8().constData(), value.toUtf8().constData());
}
} // while
if (headersFinished) {
const bool ok = checkHeaders();
if (QString gotKey;
ok && (gotKey=headers.value(QStringLiteral("sec-websocket-accept"))) != expectedDigest)
Fail(QString("Bad key: expected '%1', got '%2'").arg(QString(expectedDigest), gotKey));
if (ok) {
qDebug("Successful websocket handshake to host %s:%hu", sock->peerName().toLatin1().constData(), sock->peerPort());
{
// save some properties to the socket
sock->setProperty(kWebsocketFlag, true);
QVariantMap m;
for (auto it = headers.cbegin(); it != headers.cend(); it)
m[it.key()] = it.value();
sock->setProperty(kWebsocketHeaders, m); // save headers to sock
}
emit success();
return;
} else
Fail("Missing required headers");
}
} catch (const std::exception &e) {
qDebug("Failed handshake: %s", e.what());
emit failure(e.what());
// at this point this slot will never be called again because we auto-disconnect signals
}
} // end function ClientSide::on_ReadyRead
// --- ServerSide
ServerSide::~ServerSide(){} // for vtable
void ServerSide::start(const QString & serverAgent, int timeout)
{
if (!startCommon(timeout))
return;
reqResource.clear();
this->serverAgent = serverAgent;
// sock already had some bytes.. call on_ReadyRead() immediately
if (sock->bytesAvailable())
on_ReadyRead();
} // end function ServerSide::start
void ServerSide::on_ReadyRead()
{
bool headersFinished = false;
bool expectingReqLine = nread == 0;
try {
const auto Fail = [this](const QString &what, quint16 code = 400,
const QString & reason_ = QString(), /* Defaults to "Bad Request" */
const QString & verboseReason = QString()) {
const QString reason = reason_.isEmpty() ? QStringLiteral("Bad Request") : reason_;
const QByteArray content = verboseReason.isEmpty() ? reason.toLatin1() : verboseReason.toLatin1();
const QByteArray resp = QStringLiteral(
"HTTP/1.1 %1 %2\r\n"
"Content-Length: %3\r\n"
"Content-Type: text/plain\r\n"
"Connection: close\r\n\r\n"
"%4"
).arg(QString::number(code), reason, QString::number(content.size()), QString::fromLatin1(content)).toLatin1();
sock->write(resp);
sock->flush();
throw Exception(what);
};
while (sock->canReadLine()) {
if (maxHeaders > 0 && sock->bytesAvailable() > maxHeaders)
Fail(kMaxHeadersExceeded); // will implicitly disconnect signals from sock
auto line = sock->readLine();
nread = line.size();
if (maxHeaders > 0 && nread > maxHeaders)
Fail(kMaxHeadersExceeded);
line = line.trimmed();
if (line.isEmpty()) {
// end of headers
headersFinished = true;
break;
}
//qDebug("Got line: %s", line.constData());
if (expectingReqLine) {
// parse status line
QString method;
int major, minor;
if (!parseReqLine(line, &major, &minor, &method, &reqResource)
|| major < 1 || minor < 1 || method != "GET")
Fail(QString(kBadHttpLine).arg(QString(line)));
//qDebug("HTTP GET for: %s", reqResource.toUtf8().constData());
expectingReqLine = false;
} else {
// expecting Header: value
const auto parts = line.split(':');
if (parts.size() < 2)
Fail("Bad header line");
const QString key = QString::fromLatin1(parts.front().trimmed().toLower()),
value = QString::fromLatin1(parts.mid(1).join(':').trimmed());
headers[key] = value;
////qDebug("[Added header: %s=%s]", key.toUtf8().constData(), value.toUtf8().constData());
}
} // while
if (headersFinished) {
if (QString message; !checkHeaders(&message))
Fail(message, 426, "Upgrade Required");
QByteArray key;
if (key = headers.value(QStringLiteral("sec-websocket-key")).toLatin1();
key.isEmpty() || QByteArray::fromBase64(key).toBase64() != key) {
Fail(QString("Bad key: '%1'").arg(QString::fromLatin1(key)),
400, QString(), QStringLiteral("Invalid Sec-WebSocket-Key header: %1").arg(QString::fromLatin1(key)));
}
// -- send response header
{
constexpr auto GetHTTPDate = []{
return QLocale::c().toString(QDateTime::currentDateTime(), u"ddd, dd MMM yyyy hh:mm:ss 'GMT'");
};
const auto serverAgentTrimmed = serverAgent.trimmed();
const QByteArray header =
QStringLiteral(
"HTTP/1.1 101 Switching Protocols\r\n"
"Upgrade: websocket\r\n"
"Connection: Upgrade\r\n"
"Sec-WebSocket-Accept: %1\r\n"
"%2" // may be empty or may be "Server: serverAgent\r\n"
"Date: %3\r\n"
"\r\n"
).arg(QString(QCryptographicHash::hash(key UUID, QCryptographicHash::Algorithm::Sha1).toBase64()),
serverAgentTrimmed.isEmpty() ? QString() : QStringLiteral("Server: %1\r\n").arg(serverAgentTrimmed),
GetHTTPDate()).toLatin1();
//qDebug("Sending response header:\n%s", header.constData());
sock->write(header);
}
qDebug("Successful websocket handshake for client %s:%hu",
sock->peerAddress().toString().toUtf8().constData(), sock->peerPort());
{
// save some properties to the socket
sock->setProperty(kWebsocketFlag, true);
QVariantMap m;
for (auto it = headers.cbegin(); it != headers.cend(); it)
m[it.key()] = it.value();
sock->setProperty(kWebsocketHeaders, m); // save headers to sock
sock->setProperty(kWebsocketReqResource, reqResource);
}
emit success();
return;
}
} catch (const std::exception &e) {
qDebug("%s:%hu failed handshake: %s", sock->peerAddress().toString().toUtf8().constData(), sock->peerPort(),
e.what());
emit failure(e.what());
// at this point this slot will never be called again because we auto-disconnect signals
}
} // end function ServerSide::on_ReadyRead
} // end namespace Async
} // end namespace Handshake
// --- Wrapper
Wrapper::Wrapper(QTcpSocket *socket_, QObject *parent)
: QTcpSocket(socket_ == parent ? nullptr : parent), socket(socket_)
{
assert(socket);
assert(parent != socket_);
socket->setParent(this);
connect(socket, &QTcpSocket::readyRead, this, &Wrapper::on_readyRead);
connect(socket, &QTcpSocket::bytesWritten, this, &Wrapper::rawBytesWritten);
connect(socket, &QTcpSocket::hostFound, this, &Wrapper::hostFound);
connect(socket, &QTcpSocket::connected, this, &Wrapper::connected);
connect(socket, &QTcpSocket::disconnected, this, &Wrapper::disconnected);
connect(socket, &QTcpSocket::stateChanged, this, &Wrapper::setSocketState);
connect(socket, &QTcpSocket::stateChanged, this, &Wrapper::stateChanged);
connect(socket, Compat::SocketErrorSignalFunctionPtr<QTcpSocket>(), this, &Wrapper::setSocketError);
connect(socket, Compat::SocketErrorSignalFunctionPtr<QTcpSocket>(), this, Compat::SocketErrorSignalFunctionPtr<Wrapper>());
setOpenMode(socket->openMode());
setPeerName(socket->peerName());
setPeerAddress(socket->peerAddress());
setPeerPort(socket->peerPort());
setLocalPort(socket->localPort());
setLocalAddress(socket->localAddress());
setSocketState(socket->state());
setSocketError(socket->error());
if (socket->state() != ConnectedState) {
qCritical() << "WebSocket Wrapper may only be used with an already-connected socket";
}
// on handshake success, setup the auto-ping interval
connect(this, &Wrapper::handshakeSuccess, this, &Wrapper::startAutoPing);
// free some memory on disconnect
connect(this, &Wrapper::disconnected, this, &Wrapper::miscCleanup);
}
void Wrapper::startAutoPing() { setAutoPingInterval(autopinginterval); }
void Wrapper::miscCleanup() {
dataMessages.clear();
readDataPartialBuf.clear();
buf.clear();
}
Wrapper::~Wrapper() {
// During debug I found spuriously these signals can get delivered when we are no longer a `Wrapper`, but a