-
Notifications
You must be signed in to change notification settings - Fork 5
Expand file tree
/
Copy pathprotocol.cpp
More file actions
4488 lines (3874 loc) · 98.6 KB
/
protocol.cpp
File metadata and controls
4488 lines (3874 loc) · 98.6 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-FileCopyrightText: 2020-2026 Jochem Rutgers
//
// SPDX-License-Identifier: MPL-2.0
#include <libstored/poller.h>
#include <libstored/protocol.h>
#include <libstored/util.h>
#ifdef STORED_OS_WINDOWS
# include <fcntl.h>
# include <io.h>
#elif !defined(STORED_OS_BAREMETAL)
# include <fcntl.h>
# include <unistd.h>
#endif
#if defined(STORED_OS_POSIX)
# include <csignal>
# include <sys/stat.h>
# include <sys/types.h>
# include <termios.h>
#endif
#ifdef STORED_HAVE_ZTH
# include <zth>
# define delay_ms(ms) zth::mnap(ms)
#elif defined(STORED_OS_WINDOWS)
# define delay_ms(ms) Sleep(ms)
#else
# define delay_ms(ms) usleep((ms)*1000L)
#endif
#if defined(STORED_OS_WINDOWS)
// NOLINTNEXTLINE(cppcoreguidelines-macro-usage)
# define write(fd, buffer, count) _write(fd, buffer, (unsigned int)(count))
#endif
#include <algorithm>
#include <exception>
#include <new>
namespace stored {
//////////////////////////////
// ProtocolLayer
//
/*!
* \brief Destructor.
*
* Ties to the layer above and below are nicely removed.
*/
ProtocolLayer::~ProtocolLayer()
{
if(up() && up()->down() == this)
up()->justSetDown(down());
if(down() && down()->up() == this)
down()->justSetUp(up());
}
//////////////////////////////
// AsciiEscapeLayer
//
/*!
* \copydoc stored::ProtocolLayer::ProtocolLayer()
* \param all when \c true, convert all control characters, instead of only
* those that conflict with other protocols
*/
AsciiEscapeLayer::AsciiEscapeLayer(bool all, ProtocolLayer* up, ProtocolLayer* down)
: base(up, down)
, m_all(all)
{}
void AsciiEscapeLayer::decode(void* buffer, size_t len)
{
char* p = static_cast<char*>(buffer);
// Common case: there is no escape character.
size_t i = 0;
for(; i + 1 < len; i++)
if(unlikely(p[i] == Esc || p[i] == '\r'))
goto first_escape;
// No escape characters.
base::decode(buffer, len);
return;
first_escape:
// Process escape sequences in-place.
size_t decodeOffset = i;
if(p[i] == '\r') {
// Just drop.
} else {
escape:
if(p[++i] == Esc)
p[decodeOffset] = (char)Esc;
else
p[decodeOffset] = (char)((uint8_t)p[i] & (uint8_t)EscMask);
decodeOffset++;
}
i++;
// The + 1 prevents it from trying to decode an escape character at the end.
for(; i + 1 < len; i++, decodeOffset++) {
if(unlikely(p[i] == Esc))
goto escape;
else if(unlikely(p[i] == '\r'))
decodeOffset--;
else
p[decodeOffset] = p[i];
}
// Always add the last character (if any).
if(i < len)
p[decodeOffset++] = p[i];
base::decode(p, decodeOffset);
}
char AsciiEscapeLayer::needEscape(char c) const
{
if(!((uint8_t)c & (uint8_t) ~(uint8_t)AsciiEscapeLayer::EscMask)) {
if(!m_all) {
// Only escape what conflicts with other protocols.
switch(c) {
case '\0':
case '\x11': // XON
case '\x13': // XOFF
case '\x1b': // ESC
case '\r':
// Do escape \r, as Windows may inject it automatically. So, if \r
// is meant to be sent, escape it, such that the client may remove
// all (unescaped) \r's automatically.
break;
default:
// Don't escape.
return 0;
}
}
return (char)((uint8_t)c | 0x40U);
} else if(c == AsciiEscapeLayer::Esc) {
return c;
} else {
return 0;
}
}
void AsciiEscapeLayer::encode(void const* buffer, size_t len, bool last)
{
uint8_t const* p = static_cast<uint8_t const*>(buffer);
uint8_t const* chunk = p;
for(size_t i = 0; i < len; i++) {
char escaped = needEscape((char)p[i]);
if(unlikely(escaped)) {
// This is a to-be-escaped byte.
if(chunk < p + i)
base::encode(chunk, (size_t)(p + i - chunk), false);
uint8_t const esc[2] = {AsciiEscapeLayer::Esc, (uint8_t)escaped};
base::encode(esc, sizeof(esc), last && i + 1 == len);
chunk = p + i + 1;
}
}
if(likely(chunk < p + len) || (len == 0 && last))
base::encode(chunk, (size_t)(p + len - chunk), last);
}
size_t AsciiEscapeLayer::mtu() const
{
size_t mtu = base::mtu();
if(mtu == 0U)
return 0U;
if(mtu == 1U)
return 1U;
return mtu / 2U;
}
//////////////////////////////
// TerminalLayer
//
#if STORED_cplusplus < 201103L
/*!
* \copydoc stored::ProtocolLayer::ProtocolLayer(ProtocolLayer*,ProtocolLayer*)
* \param cb the callback to call with the data that is not part of debug messages during decode().
* Set to \c nullptr to drop this data.
*/
TerminalLayer::TerminalLayer(NonDebugDecodeCallback* cb, ProtocolLayer* up, ProtocolLayer* down)
: base(up, down)
, m_nonDebugDecodeCallback(cb)
, m_decodeState(StateNormal)
, m_encodeState()
{}
#endif
TerminalLayer::TerminalLayer(ProtocolLayer* up, ProtocolLayer* down)
: base(up, down)
#if STORED_cplusplus < 201103L
, m_nonDebugDecodeCallback()
#endif
, m_decodeState(StateNormal)
, m_encodeState()
{}
void TerminalLayer::reset()
{
m_decodeState = StateNormal;
m_encodeState = false;
m_buffer.clear();
base::reset();
}
void TerminalLayer::disconnected()
{
m_decodeState = StateNormal;
m_buffer.clear();
base::disconnected();
}
/*!
* \copydoc stored::ProtocolLayer::~ProtocolLayer()
*/
TerminalLayer::~TerminalLayer() is_default
void TerminalLayer::decode(void* buffer, size_t len)
{
size_t nonDebugOffset = m_decodeState < StateDebug ? 0 : len;
for(size_t i = 0; i < len; i++) {
char c = (static_cast<char*>(buffer))[i];
switch(m_decodeState) {
default:
case StateNormal:
if(unlikely(c == Esc))
m_decodeState = StateNormalEsc;
break;
case StateNormalEsc:
if(likely(c == EscStart)) {
if(i - nonDebugOffset > 1U)
nonDebugDecode(
static_cast<char*>(buffer) + nonDebugOffset,
i - nonDebugOffset - 1); // Also skip the ESC
m_decodeState = StateDebug;
nonDebugOffset = len;
} else
m_decodeState = StateNormal;
break;
case StateDebug:
if(unlikely(c == Esc))
m_decodeState = StateDebugEsc;
else
m_buffer.push_back(c);
break;
case StateDebugEsc:
if(likely(c == EscEnd)) {
base::decode(m_buffer.data(), m_buffer.size());
m_decodeState = StateNormal;
m_buffer.clear();
nonDebugOffset = i + 1;
} else {
m_decodeState = StateDebug;
m_buffer.push_back((char)Esc);
m_buffer.push_back(c);
}
break;
}
}
if(nonDebugOffset < len)
nonDebugDecode(static_cast<char*>(buffer) + nonDebugOffset, len - nonDebugOffset);
}
void TerminalLayer::nonDebugEncode(void const* buffer, size_t len)
{
stored_assert(!m_encodeState);
stored_assert(buffer || len == 0);
if(len)
base::encode(buffer, len, true);
}
/*!
* \brief Receptor of non-debug data during decode().
*
* Default implementation writes to the \c nonDebugDecodeFd, as supplied to the constructor.
*/
void TerminalLayer::nonDebugDecode(void* buffer, size_t len)
{
if(m_nonDebugDecodeCallback)
m_nonDebugDecodeCallback(buffer, len);
}
void TerminalLayer::encode(void const* buffer, size_t len, bool last)
{
encodeStart();
base::encode(buffer, len, false);
if(last)
encodeEnd();
}
/*!
* \brief Emits a start-of-frame sequence if it hasn't done yet.
*
* Call #encodeEnd() to finish the current frame.
*/
void TerminalLayer::encodeStart()
{
if(m_encodeState)
return;
m_encodeState = true;
char start[2] = {Esc, EscStart};
base::encode((void*)start, sizeof(start), false);
}
/*!
* \brief Emits an end-of-frame sequence of the frame started using #encodeStart().
*/
void TerminalLayer::encodeEnd()
{
if(!m_encodeState)
return;
m_encodeState = false;
char end[2] = {Esc, EscEnd};
base::encode((void*)end, sizeof(end), true);
}
size_t TerminalLayer::mtu() const
{
size_t mtu = base::mtu();
if(mtu == 0)
return 0;
if(mtu <= 4)
return 1;
return mtu - 4;
}
//////////////////////////////
// SegmentationLayer
//
/*!
* \brief Ctor.
*/
SegmentationLayer::SegmentationLayer(size_t mtu, ProtocolLayer* up, ProtocolLayer* down)
: base(up, down)
, m_mtu(mtu)
, m_lowerMtu()
, m_encoded()
{
lowerMtu();
}
void SegmentationLayer::reset()
{
m_decode.clear();
m_encoded = 0;
base::reset();
}
void SegmentationLayer::connected()
{
m_lowerMtu = lowerMtu();
if(m_lowerMtu == 0)
m_lowerMtu = std::numeric_limits<size_t>::max();
else if(m_lowerMtu == 1)
m_lowerMtu = 2;
m_encoded = 0;
base::connected();
}
void SegmentationLayer::disconnected()
{
m_decode.clear();
base::disconnected();
}
size_t SegmentationLayer::mtu() const
{
// We segment, so all layers above can use any size they want.
return 0;
}
/*!
* \brief Returns the MTU used to split messages into.
*/
size_t SegmentationLayer::lowerMtu() const
{
size_t lower_mtu = base::mtu();
if(!m_mtu)
return lower_mtu;
else if(!lower_mtu)
return m_mtu;
else
return std::min<size_t>(m_mtu, lower_mtu);
}
void SegmentationLayer::decode(void* buffer, size_t len)
{
if(len == 0)
return;
char const* buffer_ = static_cast<char*>(buffer);
if(!m_decode.empty() || buffer_[len - 1] != EndMarker) {
// Save for later packet reassembling.
if(len > 1) {
size_t start = m_decode.size();
m_decode.resize(start + len - 1);
memcpy(&m_decode[start], buffer_, len - 1);
}
if(buffer_[len - 1] == EndMarker) {
// Got it.
base::decode(m_decode.data(), m_decode.size());
m_decode.clear();
}
} else {
// Full packet is in buffer. Forward immediately.
base::decode(buffer, len - 1);
}
}
void SegmentationLayer::encode(void const* buffer, size_t len, bool last)
{
char const* buffer_ = static_cast<char const*>(buffer);
stored_assert(m_lowerMtu > m_encoded);
while(len) {
size_t remaining = m_lowerMtu - m_encoded - 1;
size_t chunk = std::min(len, remaining);
if(chunk) {
base::encode(buffer_, chunk, false);
len -= chunk;
buffer_ += chunk;
}
if(chunk == remaining && len) {
// Full MTU.
char cont = ContinueMarker;
base::encode(&cont, 1, true);
m_encoded = 0;
} else {
// Partial MTU. Record that we already filled some of the packet.
m_encoded += chunk;
}
}
if(last) {
// The marker always ends the packet.
char end = EndMarker;
base::encode(&end, 1, true);
m_encoded = 0;
}
}
//////////////////////////////
// ArqLayer
//
/*!
* \brief Ctor.
*
* If \p maxEncodeBuffer is non-zero, it defines the upper limit of the
* combined length of all queued messages for encoding. If the limit is hit,
* the #EventEncodeBufferOverflow event is passed to the callback.
*/
ArqLayer::ArqLayer(size_t maxEncodeBuffer, ProtocolLayer* up, ProtocolLayer* down)
: base(up, down)
#if STORED_cplusplus < 201103L
, m_cb()
, m_cbArg()
#endif
, m_maxEncodeBuffer(maxEncodeBuffer)
, m_encodeQueueSize()
, m_encodeState(EncodeStateIdle)
, m_connected()
, m_pauseTransmit()
, m_didTransmit()
, m_retransmits()
, m_sendSeq()
, m_recvSeq()
{
// Empty encode with seq 0, which indicates a reset message.
keepAlive();
}
/*!
* \brief Dtor.
*/
ArqLayer::~ArqLayer()
{
for(Deque<String::type*>::type::iterator it = m_encodeQueue.begin();
it != m_encodeQueue.end(); ++it)
cleanup(*it);
for(Deque<String::type*>::type::iterator it = m_spare.begin(); it != m_spare.end(); ++it)
cleanup(*it);
}
void ArqLayer::reset()
{
while(!m_encodeQueue.empty())
popEncodeQueue();
stored_assert(m_encodeQueueSize == 0);
m_encodeState = EncodeStateIdle;
m_connected = false;
m_pauseTransmit = false;
m_didTransmit = false;
m_retransmits = 0;
m_sendSeq = 0;
m_recvSeq = 0;
base::disconnected();
base::reset();
keepAlive();
}
void ArqLayer::decode(void* buffer, size_t len)
{
uint8_t* buffer_ = static_cast<uint8_t*>(buffer);
bool reset_handshake = false;
// Usually, we expect something we have to ack. Possibly a reset command to ack afterwards.
// After the response, a transmit() may be called.
uint8_t resp[2];
size_t resplen = 0;
bool do_transmit = false;
bool do_decode = false;
stored_assert(!m_pauseTransmit);
m_pauseTransmit = true;
while(len > 0) {
uint8_t const hdr = buffer_[0];
uint8_t const hdrSeq = (uint8_t)(hdr & SeqMask);
if(hdr & AckFlag) {
if(unlikely(hdrSeq == 0)) {
// This may be an ack to our reset message.
reset_handshake = true;
}
if(waitingForAck()
&& hdrSeq == ((uint8_t)(*m_encodeQueue.front())[0] & SeqMask)) {
// They got our last transmission.
popEncodeQueue();
m_retransmits = 0;
// Transmit next message, if any.
do_transmit = true;
if(unlikely(reset_handshake)) {
// This is an ack to our reset message. We are connected
// now.
m_connected = true;
m_recvSeq = nextSeq(0);
base::connected();
}
}
buffer_++;
len--;
} else if(unlikely(hdrSeq == 0)) {
// This is part of the reset handshake.
// Send ack.
// NOLINTNEXTLINE(cppcoreguidelines-pro-bounds-constant-array-index)
resp[resplen++] = (uint8_t)AckFlag;
// Drop the rest.
len = 0;
if(!reset_handshake) {
// This is an unexpected reset message. Reset communication.
pushReset();
do_transmit = true;
if(isConnected()) {
m_connected = false;
event(EventReconnect);
}
base::disconnected();
}
} else if(likely(hdrSeq == m_recvSeq)) {
// This is a proper next message.
// NOLINTNEXTLINE(cppcoreguidelines-pro-bounds-constant-array-index)
resp[resplen++] = (uint8_t)(m_recvSeq | AckFlag);
m_recvSeq = nextSeq(m_recvSeq);
do_decode = !(hdr & NopFlag);
do_transmit = true; // Send out next message.
buffer_++;
len--;
} else if(nextSeq(hdrSeq) == m_recvSeq) {
// This is a retransmit of the previous message.
// Send ack again.
// NOLINTNEXTLINE(cppcoreguidelines-pro-bounds-constant-array-index)
resp[resplen++] = (uint8_t)(hdrSeq | AckFlag);
if((hdr & NopFlag)) {
buffer_++;
len--;
} else {
// Drop remaining message, without decode.
len = 0;
}
} else {
// Drop.
len = 0;
do_transmit = true;
}
if(do_decode) {
// Rest of message is data to decode.
break;
}
if(resplen == sizeof(resp)) {
// Buffer full. Unexpected amount of responses. Drop and wait for
// retransmit.
break;
}
}
if(do_decode) {
// Do decode first, as recursive calls to decode/encode may corrupt our buffer.
resetDidTransmit();
// Decode and queue encodes only.
base::decode(buffer_, len);
if(didTransmit())
do_transmit = true;
}
// We do not expect recursion here that influence this flag.
stored_assert(m_pauseTransmit);
m_pauseTransmit = false;
if(resplen) {
// First encode the responses...
base::encode(resp, resplen, !do_transmit);
m_didTransmit = true;
}
if(do_transmit) {
// ...then a message.
if(!transmit() && resplen) {
base::encode(nullptr, 0, true);
m_didTransmit = true;
}
}
}
/*!
* \brief Checks if this layer is waiting for an ack.
*/
bool ArqLayer::waitingForAck() const
{
if(m_encodeQueue.empty())
return false;
if(m_encodeQueue.size() == 1 && m_encodeState != EncodeStateIdle)
return false;
stored_assert(m_encodeQueue.front() && !m_encodeQueue.front()->empty());
return true;
}
void ArqLayer::encode(void const* buffer, size_t len, bool last)
{
bool isIdle = !waitingForAck();
if(m_maxEncodeBuffer > 0 && m_maxEncodeBuffer < m_encodeQueueSize + len + 1U /* seq */)
event(EventEncodeBufferOverflow);
switch(m_encodeState) {
default:
case EncodeStateIdle:
pushEncodeQueue(buffer, len);
if(!last)
m_encodeState = EncodeStateEncoding;
break;
case EncodeStateEncoding:
stored_assert(!m_encodeQueue.empty());
m_encodeQueueSize += len;
m_encodeQueue.back()->append(static_cast<char const*>(buffer), len);
if(last)
m_encodeState = EncodeStateIdle;
break;
}
if(isIdle)
transmit();
}
bool ArqLayer::flush()
{
bool res = !transmit();
return base::flush() && res;
}
/*!
* \brief (Re)transmits the first message in the queue.
* \return \c true if something has been sent, \c false if the queue is empty
*/
bool ArqLayer::transmit()
{
if(m_encodeQueue.empty())
// Nothing to send.
return false;
if(m_encodeQueue.size() == 1 && m_encodeState == EncodeStateEncoding)
// Still assembling first message, but there is nothing to flush (yet).
return false;
// Update administration first, in case base::encode() has some recursive
// call back to decode()/encode().
m_didTransmit = true;
if(m_pauseTransmit)
// Only queue for now.
return false;
if(m_retransmits < std::numeric_limits<decltype(m_retransmits)>::max()) {
if(++m_retransmits % RetransmitCallbackThreshold == 0)
event(EventRetransmit);
} else {
event(EventRetransmit);
}
// (Re)transmit first message.
stored_assert(waitingForAck());
base::encode(m_encodeQueue.front()->data(), m_encodeQueue.front()->size(), true);
return true;
}
/*!
* \brief Forward the given event to the registered callback, if any.
*/
void ArqLayer::event(ArqLayer::Event e)
{
if(m_cb) {
#if STORED_cplusplus < 201103L
m_cb(*this, e, m_cbArg);
#else
m_cb(*this, e);
#endif
} else {
switch(e) {
default:
case EventNone:
case EventReconnect:
case EventRetransmit:
// By default, ignore.
break;
case EventEncodeBufferOverflow:
// Cannot handle this.
STORED_throw(std::bad_alloc());
}
}
}
/*!
* \brief Compute the next sequence number.
*/
uint8_t ArqLayer::nextSeq(uint8_t seq)
{
seq = (uint8_t)((seq + 1U) & SeqMask);
// cppcheck-suppress[knownConditionTrueFalse,unmatchedSuppression]
return seq ? seq : 1U;
}
size_t ArqLayer::mtu() const
{
size_t mtu = base::mtu();
if(mtu == 0)
return 0;
if(mtu <= 2U)
return 1U;
return mtu - 2U;
}
/*!
* \brief Checks if a full message has been transmitted.
*
* This function can be used to determine if this layer transmitted anything.
* For example, when a response is decoded, this function can be used to check
* if anything has sent back, or the message was dropped. Or, when #flush() is
* called, this flag can be used to check if anything was actually flushed.
*
* To use the function, first call #resetDidTransmit(), then execute the code
* you want to check, and then check #didTransmit().
*
* \see #resetDidTransmit()
*/
bool ArqLayer::didTransmit() const
{
return m_didTransmit;
}
/*!
* \brief Reset the flag for #didTransmit().
* \see #didTransmit()
*/
void ArqLayer::resetDidTransmit()
{
m_didTransmit = false;
}
/*!
* \brief Returns the number of consecutive retransmits of the same message.
*
* Use this function to determine whether the connection is still alive. It is
* application-defined what the threshold is of too many retransmits.
*/
size_t ArqLayer::retransmits() const
{
return m_retransmits ? m_retransmits - 1U : 0U;
}
/*!
* \brief Returns whether the connection is currently established.
*/
bool ArqLayer::isConnected() const
{
return m_connected;
}
/*!
* \brief Process queued messages.
*
* Call this function at a regular interval to retransmit messages, when necessary.
* When no messages are queued, this function does nothing.
*
* To send out keep-alive messages, use #keepAlive(). A common pattern would be to call this
* function relatively often (e.g., every 100 ms), and #keepAlive() less often (e.g., every 1
* second).
*
* \return EAGAIN when there was nothing to process, 0 when something was sent out, or an \c errno
* otherwise.
*/
int ArqLayer::process()
{
return transmit() ? 0 : EAGAIN;
}
/*!
* \brief Send a keep-alive packet to check the connection.
*
* It actually retransmits the message that is currently processed (waiting for an ack), or sends a
* dummy message in case the encode queue is empty. Either way, #retransmits() and the
* #EventRetransmit can be used afterwards to determine the quality of the link.
*
* If you want just only retransmits without sending a keep-alive when there is nothing to send, use
* #process() instead.
*/
void ArqLayer::keepAlive()
{
if(m_encodeQueue.empty()) {
// Send empty message. This will trigger (re)transmits, so a broken
// connection will be detected.
pushEncodeQueueRaw().push_back((char)(m_sendSeq | NopFlag));
m_encodeQueueSize++;
m_sendSeq = nextSeq(m_sendSeq);
}
transmit();
}
/*!
* \brief Clear encode queue and push a reset message.
*/
void ArqLayer::pushReset()
{
while(!m_encodeQueue.empty())
popEncodeQueue();
stored_assert(m_encodeQueueSize == 0);
m_sendSeq = 0;
pushEncodeQueueRaw().push_back((char)(m_sendSeq | NopFlag));
m_encodeQueueSize++;
m_sendSeq = nextSeq(m_sendSeq);
m_recvSeq = 0;
}
/*!
* \brief Drop front of encode queue.
*/
void ArqLayer::popEncodeQueue()
{
stored_assert(!m_encodeQueue.empty());
m_encodeQueueSize -= m_encodeQueue.front()->size();
m_encodeQueue.front()->clear();
#if STORED_cplusplus >= 201103L
m_spare.emplace_back(m_encodeQueue.front());
#else
m_spare.push_back(m_encodeQueue.front());
#endif
m_encodeQueue.pop_front();
}
/*!
* \brief Push the given buffer into the encode queue.
*/
void ArqLayer::pushEncodeQueue(void const* buffer, size_t len, bool back)
{
String::type& s = pushEncodeQueueRaw(back);
s.push_back((char)m_sendSeq);
s.append(static_cast<char const*>(buffer), len);
m_sendSeq = nextSeq(m_sendSeq);
m_encodeQueueSize += len + 1U;
}
/*!
* \brief Adds an entry in the encode queue, but do not populate the contents.
*
* The returned buffer can be used to put the message in. This should include
* the sequence number as the first byte.
*/
String::type& ArqLayer::pushEncodeQueueRaw(bool back)
{
String::type* s = nullptr;
if(m_spare.empty()) {
// NOLINTNEXTLINE(cppcoreguidelines-owning-memory)
s = new(allocate<String::type>()) String::type;
} else {
s = m_spare.back();
m_spare.pop_back();
}
stored_assert(s);
if(back) {
m_encodeQueue.
#if STORED_cplusplus >= 201103L
emplace_back(s);
#else
push_back(s);
#endif
} else {
m_encodeQueue.
#if STORED_cplusplus >= 201103L
emplace_front(s);
#else
push_front(s);
#endif
}
stored_assert(s->empty());
return *s;
}
/*!
* \brief Free all unused memory.
*/
void ArqLayer::shrink_to_fit()
{
for(Deque<String::type*>::type::iterator it = m_encodeQueue.begin();
it != m_encodeQueue.end(); ++it)
#if STORED_cplusplus >= 201103L
(*it)->shrink_to_fit();
#else
(*it)->reserve((*it)->size());
#endif
for(Deque<String::type*>::type::iterator it = m_spare.begin(); it != m_spare.end(); ++it)
cleanup(*it);
m_spare.clear();
#if STORED_cplusplus >= 201103L
m_spare.shrink_to_fit();
#endif
}
void ArqLayer::connected()
{
// Don't propagate the connected event. A reconnection is handled by this layer itself, via