FreeRDP
Loading...
Searching...
No Matches
TestRdpUdp.c
1
17
18/* The client side of RDP-UDP against a server played by the test over a loopback socket.
19 *
20 * Nothing in rdpudp.c is opened up for this: the test answers the SYN, sends the datagrams a
21 * Windows server would, and reads what the client delivers through its receive callback and
22 * sends back on the wire. */
23
24#include <stdio.h>
25#include <string.h>
26
27#include <winpr/wtypes.h>
28#include <winpr/crt.h>
29#include <winpr/stream.h>
30#include <winpr/synch.h>
31#include <winpr/sysinfo.h>
32#include <winpr/winsock.h>
33#include <winpr/wlog.h>
34
35#if !defined(_WIN32)
36#include <sys/socket.h>
37#include <netinet/in.h>
38#include <arpa/inet.h>
39#endif
40
41#include "../rdpudp.h"
42
43#define TAG "com.freerdp.core.test.rdpudp"
44
45/* [MS-RDPEUDP] 2.2.2.1 uFlags */
46#define FLAG_SYN 0x0001
47#define FLAG_ACK 0x0004
48#define FLAG_SYNEX 0x1000
49
50/* [MS-RDPEUDP2] 2.2.1.1 Flags */
51#define V3_ACK 0x001
52#define V3_DATA 0x004
53#define V3_ACKVEC 0x008
54#define V3_AOA 0x010
55#define V3_OVERHEADSIZE 0x040
56#define V3_DELAYACKINFO 0x100
57
58#define V3_TYPE_STANDARD 0
59#define V3_TYPE_DUMMY 8
60
61#define SYN_LENGTH 1232
62#define FIRST_SEQUENCE 100
63
64#define CHECK(cond) \
65 do \
66 { \
67 if (!(cond)) \
68 { \
69 (void)fprintf(stderr, "%s:%d: check failed: %s\n", __FILE__, __LINE__, #cond); \
70 goto fail; \
71 } \
72 } while (0)
73
74/* A datagram the client sent, decoded. */
75typedef struct
76{
77 UINT16 flags;
78 BYTE logWindow;
79 UINT16 ack;
80 BOOL hasAoA;
81 UINT16 aoa;
82 BOOL hasData;
83 UINT16 dataSeq;
84 UINT16 channelSeq;
85 BYTE payload[64];
86 size_t payloadLength;
87 UINT16 vecBase;
88 BYTE vec[127];
89 size_t vecLength;
90} V3Packet;
91
92#define MAX_SEEN 256
93
94typedef struct
95{
96 SOCKET server;
97 struct sockaddr_in serverAddr;
98 rdpUdp* udp;
99 wStream* delivered;
100
101 /* what the client sent since the last drain, the newest MAX_SEEN of it */
102 V3Packet seen[MAX_SEEN];
103 size_t seenCount;
104} TestCtx;
105
106/* ---------------------------------------------------------------------------------------- */
107/* The server's socket */
108/* ---------------------------------------------------------------------------------------- */
109
110static BOOL on_receive(void* custom, const BYTE* data, size_t length)
111{
112 TestCtx* ctx = custom;
113 if (!Stream_EnsureRemainingCapacity(ctx->delivered, length))
114 return FALSE;
115 Stream_Write(ctx->delivered, data, length);
116 return TRUE;
117}
118
119static BOOL server_open(TestCtx* ctx)
120{
121 ctx->server = _socket(AF_INET, SOCK_DGRAM, IPPROTO_UDP);
122 if (ctx->server == INVALID_SOCKET)
123 return FALSE;
124
125 struct sockaddr_in addr = WINPR_C_ARRAY_INIT;
126 addr.sin_family = AF_INET;
127 addr.sin_addr.s_addr = htonl(INADDR_LOOPBACK);
128 addr.sin_port = 0;
129 if (_bind(ctx->server, (const struct sockaddr*)&addr, sizeof(addr)) != 0)
130 return FALSE;
131
132 socklen_t length = sizeof(ctx->serverAddr);
133 if (_getsockname(ctx->server, (struct sockaddr*)&ctx->serverAddr, &length) != 0)
134 return FALSE;
135
136 u_long arg = 1;
137 return _ioctlsocket(ctx->server, FIONBIO, &arg) == 0;
138}
139
140/* One datagram from the client, waiting up to timeoutMs for it. 0 when none came. */
141static size_t server_recv(TestCtx* ctx, BYTE* buffer, size_t size, UINT32 timeoutMs)
142{
143 const UINT64 deadline = GetTickCount64() + timeoutMs;
144 while (TRUE)
145 {
146 const int rc = _recv(ctx->server, (char*)buffer, (int)size, 0);
147 if (rc > 0)
148 return (size_t)rc;
149 if (GetTickCount64() >= deadline)
150 return 0;
151 Sleep(1);
152 }
153}
154
155static BOOL server_send_raw(TestCtx* ctx, const BYTE* data, size_t length)
156{
157 return _send(ctx->server, (const char*)data, (int)length, 0) == (int)length;
158}
159
160/* Lets the client read what arrived and run its timers. */
161static BOOL pump(TestCtx* ctx)
162{
163 Sleep(1);
164 return rdpudp_check(ctx->udp);
165}
166
167/* ---------------------------------------------------------------------------------------- */
168/* RDP-UDP2 packets ([MS-RDPEUDP2] 2.2.1) */
169/* ---------------------------------------------------------------------------------------- */
170
171static void write_uint24(wStream* s, UINT32 value)
172{
173 Stream_Write_UINT8(s, (BYTE)(value & 0xFF));
174 Stream_Write_UINT8(s, (BYTE)((value >> 8) & 0xFF));
175 Stream_Write_UINT8(s, (BYTE)((value >> 16) & 0xFF));
176}
177
178/* What the test server puts in one packet. */
179typedef struct
180{
181 BOOL dummy;
182 BOOL hasAck;
183 UINT16 ack;
184 BOOL hasDelayAck;
185 BYTE maxDelayedAcks;
186 UINT16 delayedAckTimeout;
187 BOOL hasAoA;
188 UINT16 aoa;
189 BOOL hasData;
190 UINT16 dataSeq;
191 UINT16 channelSeq;
192 const BYTE* payload;
193 size_t payloadLength;
194} V3Out;
195
196/* Encodes the packet the way Windows puts it on the wire: prefix byte in front, a short layout
197 * padded to 7 bytes, then the first and eighth byte swapped. */
198static BOOL server_send_v3(TestCtx* ctx, const V3Out* out)
199{
200 BYTE wire[1500] = WINPR_C_ARRAY_INIT;
201 wStream sbuffer = WINPR_C_ARRAY_INIT;
202 wStream* s = Stream_StaticInit(&sbuffer, wire, sizeof(wire));
203
204 UINT16 flags = 0;
205 if (out->hasAck)
206 flags |= V3_ACK;
207 if (out->hasDelayAck)
208 flags |= V3_DELAYACKINFO;
209 if (out->hasAoA)
210 flags |= V3_AOA;
211 if (out->hasData)
212 flags |= V3_DATA;
213
214 Stream_Seek(s, 1); /* the prefix byte */
215 Stream_Write_UINT16(s, (UINT16)(flags | (15u << 12)));
216 if (out->hasAck)
217 {
218 Stream_Write_UINT16(s, out->ack); /* SeqNum */
219 write_uint24(s, 0); /* receivedTS */
220 Stream_Write_UINT8(s, 0); /* sendAckTimeGapInMs */
221 Stream_Write_UINT8(s, 0); /* numDelayedAcks */
222 }
223 if (out->hasDelayAck)
224 {
225 Stream_Write_UINT8(s, out->maxDelayedAcks); /* MaxDelayedAcks */
226 Stream_Write_UINT16(s, out->delayedAckTimeout); /* DelayedAckTimeoutInMs */
227 }
228 if (out->hasAoA)
229 Stream_Write_UINT16(s, out->aoa);
230 if (out->hasData)
231 {
232 Stream_Write_UINT16(s, out->dataSeq);
233 Stream_Write_UINT16(s, out->channelSeq);
234 Stream_Write(s, out->payload, out->payloadLength);
235 }
236
237 const size_t layout = Stream_GetPosition(s) - 1;
238 BYTE shortLength = 7;
239 if (layout < 7)
240 {
241 shortLength = (BYTE)layout;
242 Stream_Zero(s, 7 - layout);
243 }
244 const size_t length = Stream_GetPosition(s);
245 const BYTE type = out->dummy ? V3_TYPE_DUMMY : V3_TYPE_STANDARD;
246 wire[0] = (BYTE)((shortLength << 5) | (type << 1));
247 const BYTE eighth = wire[7];
248 wire[7] = wire[0];
249 wire[0] = eighth;
250 return server_send_raw(ctx, wire, length);
251}
252
253static BOOL send_data(TestCtx* ctx, UINT16 dataSeq, UINT16 channelSeq, const char* text)
254{
255 const V3Out out = { .hasData = TRUE,
256 .dataSeq = dataSeq,
257 .channelSeq = channelSeq,
258 .payload = (const BYTE*)text,
259 .payloadLength = strlen(text) };
260 return server_send_v3(ctx, &out);
261}
262
263static BOOL send_aoa(TestCtx* ctx, UINT16 aoa)
264{
265 const V3Out out = { .hasAoA = TRUE, .aoa = aoa };
266 return server_send_v3(ctx, &out);
267}
268
269static BOOL send_ack(TestCtx* ctx, UINT16 ack)
270{
271 const V3Out out = { .hasAck = TRUE, .ack = ack };
272 return server_send_v3(ctx, &out);
273}
274
275static BOOL parse_v3(const BYTE* wire, size_t length, V3Packet* packet)
276{
277 BYTE buffer[1500] = WINPR_C_ARRAY_INIT;
278 if ((length < 8) || (length > sizeof(buffer)))
279 return FALSE;
280 memcpy(buffer, wire, length);
281 const BYTE eighth = buffer[7];
282 buffer[7] = buffer[0];
283 buffer[0] = eighth;
284
285 memset(packet, 0, sizeof(*packet));
286 const BYTE prefix = buffer[0];
287 const BYTE shortLength = prefix >> 5;
288 if (shortLength < 7)
289 length = 1ull + shortLength;
290
291 wStream sbuffer = WINPR_C_ARRAY_INIT;
292 wStream* s = Stream_StaticConstInit(&sbuffer, buffer + 1, length - 1);
293 if (!Stream_CheckAndLogRequiredLength(TAG, s, 2))
294 return FALSE;
295 const UINT16 header = Stream_Get_UINT16(s);
296 packet->flags = header & 0x0FFF;
297 packet->logWindow = (BYTE)(header >> 12);
298
299 if (packet->flags & V3_ACK)
300 {
301 if (!Stream_CheckAndLogRequiredLength(TAG, s, 7))
302 return FALSE;
303 packet->ack = Stream_Get_UINT16(s);
304 Stream_Seek(s, 4); /* receivedTS, sendAckTimeGapInMs */
305 const size_t delayed = Stream_Get_UINT8(s) & 0x0F;
306 if (!Stream_SafeSeek(s, delayed))
307 return FALSE;
308 }
309 if ((packet->flags & V3_OVERHEADSIZE) && !Stream_SafeSeek(s, 1))
310 return FALSE;
311 if ((packet->flags & V3_DELAYACKINFO) && !Stream_SafeSeek(s, 3))
312 return FALSE;
313 if (packet->flags & V3_AOA)
314 {
315 if (!Stream_CheckAndLogRequiredLength(TAG, s, 2))
316 return FALSE;
317 packet->hasAoA = TRUE;
318 packet->aoa = Stream_Get_UINT16(s);
319 }
320 if (packet->flags & V3_DATA)
321 {
322 if (!Stream_CheckAndLogRequiredLength(TAG, s, 2))
323 return FALSE;
324 packet->dataSeq = Stream_Get_UINT16(s);
325 }
326 if (packet->flags & V3_ACKVEC)
327 {
328 if (!Stream_CheckAndLogRequiredLength(TAG, s, 3))
329 return FALSE;
330 packet->vecBase = Stream_Get_UINT16(s);
331 const BYTE control = Stream_Get_UINT8(s);
332 if ((control & 0x80) && !Stream_SafeSeek(s, 4)) /* TimeStamp, SendAckTimeGapInMs */
333 return FALSE;
334 packet->vecLength = control & 0x7F;
335 if (!Stream_CheckAndLogRequiredLength(TAG, s, packet->vecLength))
336 return FALSE;
337 Stream_Read(s, packet->vec, packet->vecLength);
338 }
339 if (packet->flags & V3_DATA)
340 {
341 if (!Stream_CheckAndLogRequiredLength(TAG, s, 2))
342 return FALSE;
343 packet->hasData = TRUE;
344 packet->channelSeq = Stream_Get_UINT16(s);
345 packet->payloadLength = Stream_GetRemainingLength(s);
346 if (packet->payloadLength > sizeof(packet->payload))
347 packet->payloadLength = sizeof(packet->payload);
348 Stream_Read(s, packet->payload, packet->payloadLength);
349 }
350 return TRUE;
351}
352
353/* Reads everything the client sent, until nothing more arrives for waitMs. */
354static BOOL drain(TestCtx* ctx, UINT32 waitMs)
355{
356 BYTE buffer[1500] = WINPR_C_ARRAY_INIT;
357 ctx->seenCount = 0;
358 size_t length = 0;
359 while ((length = server_recv(ctx, buffer, sizeof(buffer), waitMs)) > 0)
360 {
361 V3Packet packet = WINPR_C_ARRAY_INIT;
362 if (!parse_v3(buffer, length, &packet))
363 return FALSE;
364 if (ctx->seenCount == MAX_SEEN)
365 {
366 memmove(&ctx->seen[0], &ctx->seen[1], sizeof(ctx->seen[0]) * (MAX_SEEN - 1));
367 ctx->seenCount--;
368 }
369 ctx->seen[ctx->seenCount++] = packet;
370 }
371 return TRUE;
372}
373
374/* Reads what the client sent until want DATA packets are in, or timeoutMs passed. */
375static BOOL collect_data(TestCtx* ctx, size_t want, UINT32 timeoutMs)
376{
377 BYTE buffer[1500] = WINPR_C_ARRAY_INIT;
378 ctx->seenCount = 0;
379 size_t count = 0;
380 while (count < want)
381 {
382 const size_t length = server_recv(ctx, buffer, sizeof(buffer), timeoutMs);
383 if (length == 0)
384 return FALSE;
385 if (ctx->seenCount == MAX_SEEN)
386 return FALSE;
387 V3Packet* packet = &ctx->seen[ctx->seenCount++];
388 if (!parse_v3(buffer, length, packet))
389 return FALSE;
390 if (packet->hasData)
391 count++;
392 }
393 return TRUE;
394}
395
396/* The newest acknowledgement the client sent, ACK or ACK vector. */
397static const V3Packet* last_ack(const TestCtx* ctx)
398{
399 for (size_t x = ctx->seenCount; x > 0; x--)
400 {
401 const V3Packet* packet = &ctx->seen[x - 1];
402 if (packet->flags & (V3_ACK | V3_ACKVEC))
403 return packet;
404 }
405 return nullptr;
406}
407
408static size_t count_data(const TestCtx* ctx)
409{
410 size_t count = 0;
411 for (size_t x = 0; x < ctx->seenCount; x++)
412 {
413 if (ctx->seen[x].hasData)
414 count++;
415 }
416 return count;
417}
418
419static const V3Packet* first_data(const TestCtx* ctx)
420{
421 for (size_t x = 0; x < ctx->seenCount; x++)
422 {
423 if (ctx->seen[x].hasData)
424 return &ctx->seen[x];
425 }
426 return nullptr;
427}
428
429static BOOL delivered_is(const TestCtx* ctx, const char* expected)
430{
431 const size_t length = strlen(expected);
432 return (Stream_GetPosition(ctx->delivered) == length) &&
433 (memcmp(Stream_Buffer(ctx->delivered), expected, length) == 0);
434}
435
436/* What was delivered after the first offset bytes. */
437static BOOL delivered_tail_is(const TestCtx* ctx, size_t offset, const char* expected)
438{
439 const size_t length = strlen(expected);
440 return (Stream_GetPosition(ctx->delivered) == offset + length) &&
441 (memcmp(Stream_Buffer(ctx->delivered) + offset, expected, length) == 0);
442}
443
444/* ---------------------------------------------------------------------------------------- */
445/* Connection setup */
446/* ---------------------------------------------------------------------------------------- */
447
448static const BYTE cookieHash[32] = { 0xAA, 0xAA, 0xAA, 0xAA, 0xAA, 0xAA, 0xAA, 0xAA,
449 0xAA, 0xAA, 0xAA, 0xAA, 0xAA, 0xAA, 0xAA, 0xAA,
450 0xAA, 0xAA, 0xAA, 0xAA, 0xAA, 0xAA, 0xAA, 0xAA,
451 0xAA, 0xAA, 0xAA, 0xAA, 0xAA, 0xAA, 0xAA, 0xAA };
452
453typedef struct
454{
455 size_t length;
456 UINT16 flags;
457 UINT32 initialSequence;
458 UINT16 version;
459 BYTE cookie[32];
460 BYTE raw[SYN_LENGTH]; /* the datagram as it came */
461} SynInfo;
462
463static void ctx_free(TestCtx* ctx)
464{
465 rdpudp_free(ctx->udp);
466 if (ctx->server != INVALID_SOCKET)
467 closesocket(ctx->server);
468 Stream_Free(ctx->delivered, TRUE);
469 memset(ctx, 0, sizeof(*ctx));
470 ctx->server = INVALID_SOCKET;
471}
472
473/* Starts the client and reads its SYN, the connection is left in SYN_SENT. */
474static BOOL ctx_start(TestCtx* ctx, BOOL offerV3, SynInfo* syn)
475{
476 memset(ctx, 0, sizeof(*ctx));
477 ctx->server = INVALID_SOCKET;
478 ctx->delivered = Stream_New(nullptr, 1024);
479 if (!ctx->delivered || !server_open(ctx))
480 return FALSE;
481
482 ctx->udp = rdpudp_new(WLog_Get(TAG), offerV3 ? cookieHash : nullptr, on_receive, ctx);
483 if (!ctx->udp)
484 return FALSE;
485 if (!rdpudp_connect(ctx->udp, (const struct sockaddr*)&ctx->serverAddr,
486 sizeof(ctx->serverAddr)))
487 return FALSE;
488
489 BYTE buffer[1500] = WINPR_C_ARRAY_INIT;
490 struct sockaddr_in from = WINPR_C_ARRAY_INIT;
491 int fromLength = sizeof(from);
492 const UINT64 deadline = GetTickCount64() + 1000;
493 int rc = -1;
494 while ((rc = _recvfrom(ctx->server, (char*)buffer, sizeof(buffer), 0, (struct sockaddr*)&from,
495 &fromLength)) <= 0)
496 {
497 if (GetTickCount64() >= deadline)
498 return FALSE;
499 Sleep(1);
500 }
501 if (_connect(ctx->server, (const struct sockaddr*)&from, fromLength) != 0)
502 return FALSE;
503
504 wStream sbuffer = WINPR_C_ARRAY_INIT;
505 wStream* s = Stream_StaticConstInit(&sbuffer, buffer, (size_t)rc);
506 if (!Stream_CheckAndLogRequiredLength(TAG, s, 20))
507 return FALSE;
508 syn->length = (size_t)rc;
509 if (syn->length <= sizeof(syn->raw))
510 memcpy(syn->raw, buffer, syn->length);
511 Stream_Seek(s, 6); /* snSourceAck, uReceiveWindowSize */
512 syn->flags = Stream_Get_UINT16_BE(s);
513 syn->initialSequence = Stream_Get_UINT32_BE(s);
514 Stream_Seek(s, 6); /* MTUs, uSynExFlags */
515 syn->version = Stream_Get_UINT16_BE(s);
516 if (Stream_GetRemainingLength(s) >= sizeof(syn->cookie))
517 Stream_Read(s, syn->cookie, sizeof(syn->cookie));
518 return TRUE;
519}
520
521static BOOL send_syn_ack(TestCtx* ctx, UINT32 acknowledged, UINT16 version)
522{
523 BYTE wire[20] = WINPR_C_ARRAY_INIT;
524 wStream sbuffer = WINPR_C_ARRAY_INIT;
525 wStream* s = Stream_StaticInit(&sbuffer, wire, sizeof(wire));
526 Stream_Write_UINT32_BE(s, acknowledged); /* snSourceAck */
527 Stream_Write_UINT16_BE(s, 64); /* uReceiveWindowSize */
528 Stream_Write_UINT16_BE(s, FLAG_SYN | FLAG_ACK | FLAG_SYNEX);
529 Stream_Write_UINT32_BE(s, 0x1000); /* snInitialSequenceNumber */
530 Stream_Write_UINT16_BE(s, SYN_LENGTH);
531 Stream_Write_UINT16_BE(s, SYN_LENGTH);
532 Stream_Write_UINT16_BE(s, 0x0001); /* RDPUDP_VERSION_INFO_VALID */
533 Stream_Write_UINT16_BE(s, version);
534 return server_send_raw(ctx, wire, sizeof(wire));
535}
536
537/* A client connected with RDP-UDP version 3, the way a Windows server answers. */
538static BOOL ctx_connect(TestCtx* ctx)
539{
540 SynInfo syn = WINPR_C_ARRAY_INIT;
541 if (!ctx_start(ctx, TRUE, &syn))
542 return FALSE;
543 if (!send_syn_ack(ctx, syn.initialSequence, RDPUDP_PROTOCOL_VERSION_3))
544 return FALSE;
545 for (size_t x = 0; x < 100; x++)
546 {
547 if (!pump(ctx))
548 return FALSE;
549 if (rdpudp_get_state(ctx->udp) == RDPUDP_STATE_ESTABLISHED)
550 return rdpudp_get_version(ctx->udp) == RDPUDP_PROTOCOL_VERSION_3;
551 }
552 return FALSE;
553}
554
555/* Delivers count chunks of one byte from the server, the stream moving on from channel
556 * sequence *channel and data sequence *dataSeq. A batch stays well inside the socket buffer of
557 * the client, which loses datagrams beyond it like any other. */
558static BOOL stream_ahead(TestCtx* ctx, UINT16* dataSeq, UINT16* channel, size_t count)
559{
560 while (count > 0)
561 {
562 const size_t batch = (count > 64) ? 64 : count;
563 for (size_t x = 0; x < batch; x++)
564 {
565 if (!send_data(ctx, *dataSeq, *channel, "."))
566 return FALSE;
567 (*dataSeq)++;
568 (*channel)++;
569 }
570 if (!pump(ctx) || !drain(ctx, 0))
571 return FALSE;
572 count -= batch;
573 }
574 return TRUE;
575}
576
577/* ---------------------------------------------------------------------------------------- */
578/* The SYN exchange */
579/* ---------------------------------------------------------------------------------------- */
580
581static BOOL syn_offers_version_3_with_the_cookie_hash(void)
582{
583 BOOL rc = FALSE;
584 TestCtx ctx = WINPR_C_ARRAY_INIT;
585 SynInfo syn = WINPR_C_ARRAY_INIT;
586 CHECK(ctx_start(&ctx, TRUE, &syn));
587 /* [MS-RDPEUDP] 3.1.5.1.1: zero padded to the MTU, which validates the path MTU */
588 CHECK(syn.length == SYN_LENGTH);
589 CHECK((syn.flags & (FLAG_SYN | FLAG_SYNEX)) == (FLAG_SYN | FLAG_SYNEX));
590 CHECK(syn.version == RDPUDP_PROTOCOL_VERSION_3);
591 CHECK(memcmp(syn.cookie, cookieHash, sizeof(cookieHash)) == 0);
592 rc = TRUE;
593fail:
594 ctx_free(&ctx);
595 return rc;
596}
597
598static BOOL syn_offers_version_2_without_a_cookie_hash(void)
599{
600 BOOL rc = FALSE;
601 TestCtx ctx = WINPR_C_ARRAY_INIT;
602 SynInfo syn = WINPR_C_ARRAY_INIT;
603 CHECK(ctx_start(&ctx, FALSE, &syn));
604 CHECK(syn.length == SYN_LENGTH);
605 CHECK(syn.version == RDPUDP_PROTOCOL_VERSION_2);
606 rc = TRUE;
607fail:
608 ctx_free(&ctx);
609 return rc;
610}
611
612/* ---------------------------------------------------------------------------------------- */
613/* Receiving */
614/* ---------------------------------------------------------------------------------------- */
615
616static BOOL dummy_packets_are_acknowledged_but_not_delivered(void)
617{
618 BOOL rc = FALSE;
619 TestCtx ctx = WINPR_C_ARRAY_INIT;
620 CHECK(ctx_connect(&ctx));
621
622 const V3Out dummy = { .dummy = TRUE,
623 .hasData = TRUE,
624 .dataSeq = FIRST_SEQUENCE,
625 .channelSeq = 1,
626 .payload = (const BYTE*)"junk",
627 .payloadLength = 4 };
628 CHECK(server_send_v3(&ctx, &dummy));
629 CHECK(pump(&ctx));
630 CHECK(delivered_is(&ctx, ""));
631
632 /* the dummy took no channel sequence, this is the first chunk of the stream */
633 CHECK(send_data(&ctx, FIRST_SEQUENCE + 1, 1, "payload"));
634 CHECK(pump(&ctx));
635 CHECK(delivered_is(&ctx, "payload"));
636
637 CHECK(drain(&ctx, 20));
638 const V3Packet* ack = last_ack(&ctx);
639 CHECK(ack && (ack->flags & V3_ACK));
640 CHECK(ack->ack == FIRST_SEQUENCE + 1);
641 rc = TRUE;
642fail:
643 ctx_free(&ctx);
644 return rc;
645}
646
647/* A lost chunk comes back under a new data sequence number with its original channel sequence,
648 * so it arrives after the chunks that follow it. Handing the stream up in arrival order
649 * corrupts the TLS record layer above. */
650static BOOL retransmission_is_reordered_back_into_the_stream(void)
651{
652 BOOL rc = FALSE;
653 TestCtx ctx = WINPR_C_ARRAY_INIT;
654 CHECK(ctx_connect(&ctx));
655 CHECK(send_data(&ctx, 100, 1, "a"));
656 CHECK(send_data(&ctx, 101, 3, "c"));
657 CHECK(send_data(&ctx, 102, 4, "d"));
658 CHECK(pump(&ctx));
659 CHECK(delivered_is(&ctx, "a"));
660
661 CHECK(send_data(&ctx, 103, 2, "b"));
662 CHECK(pump(&ctx));
663 CHECK(delivered_is(&ctx, "abcd"));
664 rc = TRUE;
665fail:
666 ctx_free(&ctx);
667 return rc;
668}
669
670/* An AckOfAcks writes off a data sequence number the peer stopped resending (a dummy). It moves
671 * the window, the stream is ordered by channel sequence and stays as it is. */
672static BOOL ack_of_acks_advances_the_window_without_touching_the_stream(void)
673{
674 BOOL rc = FALSE;
675 TestCtx ctx = WINPR_C_ARRAY_INIT;
676 CHECK(ctx_connect(&ctx));
677 CHECK(send_data(&ctx, 100, 1, "a"));
678 /* 101 is a dummy that never arrives */
679 CHECK(send_data(&ctx, 102, 2, "b"));
680 CHECK(pump(&ctx));
681 CHECK(delivered_is(&ctx, "ab"));
682 CHECK(drain(&ctx, 20));
683 const V3Packet* ack = last_ack(&ctx);
684 CHECK(ack && (ack->flags & V3_ACKVEC) && (ack->vecBase == 101));
685
686 CHECK(send_aoa(&ctx, 102));
687 CHECK(pump(&ctx));
688 CHECK(drain(&ctx, 20));
689 ack = last_ack(&ctx);
690 CHECK(ack && (ack->flags & V3_ACK));
691 CHECK(ack->ack == 102);
692 CHECK(delivered_is(&ctx, "ab"));
693 rc = TRUE;
694fail:
695 ctx_free(&ctx);
696 return rc;
697}
698
699/* An AckOfAcks with nothing else is how a server that has heard nothing for 8 seconds asks
700 * whether the client is still there. Each one is answered with an ACK at once: the next
701 * keepalive could be 4 seconds away, and the server's timeout closer than that. */
702static BOOL ack_of_acks_on_its_own_is_answered(void)
703{
704 BOOL rc = FALSE;
705 TestCtx ctx = WINPR_C_ARRAY_INIT;
706 CHECK(ctx_connect(&ctx));
707 CHECK(send_data(&ctx, 100, 1, "a"));
708 CHECK(pump(&ctx));
709 CHECK(drain(&ctx, 30));
710 const V3Packet* ack = last_ack(&ctx);
711 CHECK(ack && (ack->flags & V3_ACK) && (ack->ack == 100));
712
713 for (size_t x = 0; x < 2; x++)
714 {
715 /* the base the client is at: nothing moves, and it still answers */
716 CHECK(send_aoa(&ctx, 101));
717 CHECK(pump(&ctx));
718 CHECK(drain(&ctx, 30));
719 ack = last_ack(&ctx);
720 CHECK(ack && (ack->flags & V3_ACK) && (ack->ack == 100));
721 }
722 CHECK(delivered_is(&ctx, "a"));
723 rc = TRUE;
724fail:
725 ctx_free(&ctx);
726 return rc;
727}
728
729static BOOL send_data_aoa(TestCtx* ctx, UINT16 dataSeq, UINT16 channelSeq, const char* text,
730 UINT16 aoa)
731{
732 const V3Out out = { .hasAoA = TRUE,
733 .aoa = aoa,
734 .hasData = TRUE,
735 .dataSeq = dataSeq,
736 .channelSeq = channelSeq,
737 .payload = (const BYTE*)text,
738 .payloadLength = strlen(text) };
739 return server_send_v3(ctx, &out);
740}
741
742/* Windows at times sends a data packet with the next sequence number as its AckOfAcks, past the
743 * packet itself. Its chunk is still data: dropped but acknowledged, it is never resent and the
744 * stream stops for good behind it. */
745static BOOL ack_of_acks_past_its_own_packet_keeps_the_chunk(void)
746{
747 BOOL rc = FALSE;
748 TestCtx ctx = WINPR_C_ARRAY_INIT;
749 CHECK(ctx_connect(&ctx));
750 CHECK(send_data(&ctx, 100, 1, "a"));
751 CHECK(send_data_aoa(&ctx, 101, 2, "b", 102));
752 CHECK(send_data_aoa(&ctx, 102, 3, "c", 102));
753 CHECK(pump(&ctx));
754 CHECK(delivered_is(&ctx, "abc"));
755 CHECK(drain(&ctx, 20));
756 const V3Packet* ack = last_ack(&ctx);
757 CHECK(ack && (ack->flags & V3_ACK) && (ack->ack == 102));
758 rc = TRUE;
759fail:
760 ctx_free(&ctx);
761 return rc;
762}
763
764/* With its AckOfAcks past the packet itself, the peer has the acknowledgment for that packet
765 * already. Windows ends the connection on an ACK vector reporting it: 00e4 with AckOfAcks 00e5 in
766 * a capture, its ACK vector followed 0.8 s later. */
767static BOOL ack_of_acks_past_its_own_packet_gets_no_ack_vector(void)
768{
769 BOOL rc = FALSE;
770 TestCtx ctx = WINPR_C_ARRAY_INIT;
771 CHECK(ctx_connect(&ctx));
772 CHECK(send_data(&ctx, 100, 1, "a"));
773 CHECK(pump(&ctx));
774 CHECK(drain(&ctx, 20));
775
776 CHECK(send_data_aoa(&ctx, 101, 2, "b", 102));
777 CHECK(send_data_aoa(&ctx, 102, 3, "c", 102));
778 CHECK(pump(&ctx));
779 CHECK(delivered_is(&ctx, "abc"));
780 CHECK(drain(&ctx, 20));
781 for (size_t x = 0; x < ctx.seenCount; x++)
782 CHECK(!(ctx.seen[x].flags & V3_ACKVEC));
783 const V3Packet* ack = last_ack(&ctx);
784 CHECK(ack && (ack->flags & V3_ACK) && (ack->ack == 102));
785 rc = TRUE;
786fail:
787 ctx_free(&ctx);
788 return rc;
789}
790
791/* The same further ahead: the chunk is kept and the sequence numbers the AckOfAcks gives up are
792 * not reported missing afterwards. */
793static BOOL ack_of_acks_far_past_its_own_packet_keeps_the_chunk(void)
794{
795 BOOL rc = FALSE;
796 TestCtx ctx = WINPR_C_ARRAY_INIT;
797 CHECK(ctx_connect(&ctx));
798 CHECK(send_data(&ctx, 100, 1, "a"));
799 CHECK(send_data_aoa(&ctx, 101, 2, "b", 104));
800 CHECK(send_data(&ctx, 104, 3, "c"));
801 CHECK(pump(&ctx));
802 CHECK(delivered_is(&ctx, "abc"));
803 CHECK(drain(&ctx, 20));
804 const V3Packet* ack = last_ack(&ctx);
805 CHECK(ack && (ack->flags & V3_ACK) && (ack->ack == 104));
806 rc = TRUE;
807fail:
808 ctx_free(&ctx);
809 return rc;
810}
811
812/* A packet the peer gave up on with an AckOfAcks can still arrive late. Its chunk fills the hole
813 * at once ([MS-RDPEUDP2] 3.1.1.2.4.2), and the resend that follows is not handed up twice. */
814static BOOL late_packet_behind_the_window_fills_the_hole(void)
815{
816 BOOL rc = FALSE;
817 TestCtx ctx = WINPR_C_ARRAY_INIT;
818 CHECK(ctx_connect(&ctx));
819 CHECK(send_data(&ctx, 100, 1, "a"));
820 /* 101, carrying channel sequence 2, is delayed */
821 CHECK(send_data(&ctx, 102, 3, "c"));
822 CHECK(send_aoa(&ctx, 102));
823 CHECK(pump(&ctx));
824 CHECK(delivered_is(&ctx, "a"));
825
826 CHECK(send_data(&ctx, 101, 2, "b"));
827 CHECK(pump(&ctx));
828 CHECK(delivered_is(&ctx, "abc"));
829
830 /* the peer's resend of channel sequence 2 */
831 CHECK(send_data(&ctx, 103, 2, "b"));
832 CHECK(send_data(&ctx, 104, 4, "d"));
833 CHECK(pump(&ctx));
834 CHECK(delivered_is(&ctx, "abcd"));
835 rc = TRUE;
836fail:
837 ctx_free(&ctx);
838 return rc;
839}
840
841/* The peer resends a packet when our acknowledgement got lost. Staying silent would make it
842 * resend until it gives up. */
843static BOOL retransmitted_packets_are_acknowledged_again(void)
844{
845 BOOL rc = FALSE;
846 TestCtx ctx = WINPR_C_ARRAY_INIT;
847 CHECK(ctx_connect(&ctx));
848 CHECK(send_data(&ctx, 100, 1, "first"));
849 CHECK(pump(&ctx));
850 CHECK(drain(&ctx, 20));
851 CHECK(last_ack(&ctx));
852
853 CHECK(send_data(&ctx, 100, 1, "first"));
854 CHECK(pump(&ctx));
855 CHECK(delivered_is(&ctx, "first"));
856 CHECK(drain(&ctx, 20));
857 /* behind the window now, it is acknowledged on its own: one run of one received packet */
858 const V3Packet* ack = last_ack(&ctx);
859 CHECK(ack && (ack->flags & V3_ACKVEC) && (ack->vecBase == 100) && (ack->vecLength == 1) &&
860 (ack->vec[0] == (0x80 | 0x40 | 1)));
861 rc = TRUE;
862fail:
863 ctx_free(&ctx);
864 return rc;
865}
866
867typedef struct
868{
869 BOOL hasAck;
870 UINT16 ack;
871 BOOL hasVector;
872 UINT16 vectorBase;
873 UINT16 lastChannel;
874 UINT16 watchedChannel;
875 UINT32 watchedSends;
876 size_t delivered; /* Number of data chunks passed to the receive callback */
877 size_t sends; /* Total number of datagrams sent */
878 size_t dataSends; /* Number of datagrams carrying data */
879 size_t aoaSends; /* Count of data datagrams that also carry AckOfAcks */
880 size_t baseSends; /* Datagrams with an AckOfAcks and nothing else */
881 UINT16 base; /* The AckOfAcks of the last of those */
882 BOOL hasDataSeq;
883 UINT16 lastDataSeq; /* Sequence number of the most recent data datagram */
884} ServerSent;
885
886/* Server test clock in nanoseconds; advanced manually instead of sleeping. */
887static UINT64 g_serverTime = 1000000000000ULL;
888
889static UINT64 server_clock(WINPR_ATTR_UNUSED void* custom)
890{
891 return g_serverTime;
892}
893
894static BOOL server_on_receive(void* custom, WINPR_ATTR_UNUSED const BYTE* data,
895 WINPR_ATTR_UNUSED size_t length)
896{
897 ServerSent* sent = custom;
898 sent->delivered++;
899 return TRUE;
900}
901
902static BOOL server_on_send(void* custom, const BYTE* data, size_t length)
903{
904 ServerSent* sent = custom;
905 sent->sends++;
906 V3Packet packet = WINPR_C_ARRAY_INIT;
907 if (!parse_v3(data, length, &packet))
908 return TRUE;
909 if (packet.flags & V3_ACK)
910 {
911 sent->hasAck = TRUE;
912 sent->ack = packet.ack;
913 }
914 if (packet.flags & V3_ACKVEC)
915 {
916 sent->hasVector = TRUE;
917 sent->vectorBase = packet.vecBase;
918 }
919 if (packet.hasAoA && !packet.hasData && !(packet.flags & (V3_ACK | V3_ACKVEC)))
920 {
921 sent->baseSends++;
922 sent->base = packet.aoa;
923 }
924 if (packet.hasData)
925 {
926 sent->hasDataSeq = TRUE;
927 sent->lastDataSeq = packet.dataSeq;
928 sent->lastChannel = packet.channelSeq;
929 if (packet.channelSeq == sent->watchedChannel)
930 sent->watchedSends++;
931 sent->dataSends++;
932 if (packet.hasAoA)
933 sent->aoaSends++;
934 }
935 return TRUE;
936}
937
938static BOOL server_receive_data(rdpUdp* udp, UINT16 dataSeq, UINT16 channelSeq)
939{
940 BYTE wire[32] = WINPR_C_ARRAY_INIT;
941 wStream sbuffer = WINPR_C_ARRAY_INIT;
942 wStream* s = Stream_StaticInit(&sbuffer, wire, sizeof(wire));
943 Stream_Seek(s, 1); /* Skip the prefix byte */
944 Stream_Write_UINT16(s, (UINT16)(V3_DATA | (15u << 12)));
945 Stream_Write_UINT16(s, dataSeq);
946 Stream_Write_UINT16(s, channelSeq);
947 Stream_Write(s, "abcd", 4);
948 const size_t length = Stream_GetPosition(s);
949 wire[0] = (BYTE)((7 << 5) | (V3_TYPE_STANDARD << 1));
950 const BYTE eighth = wire[7];
951 wire[7] = wire[0];
952 wire[0] = eighth;
953 return rdpudp_receive(udp, wire, length);
954}
955
956/* Data packet containing an AckOfAcks (AOA). */
957static BOOL server_receive_data_with_aoa(rdpUdp* udp, UINT16 dataSeq, UINT16 channelSeq, UINT16 aoa)
958{
959 BYTE wire[32] = WINPR_C_ARRAY_INIT;
960 wStream sbuffer = WINPR_C_ARRAY_INIT;
961 wStream* s = Stream_StaticInit(&sbuffer, wire, sizeof(wire));
962 Stream_Seek(s, 1); /* Skip the prefix byte */
963 Stream_Write_UINT16(s, (UINT16)(V3_DATA | V3_AOA | (15u << 12)));
964 Stream_Write_UINT16(s, aoa); /* Write the AckOfAcks field */
965 Stream_Write_UINT16(s, dataSeq);
966 Stream_Write_UINT16(s, channelSeq);
967 Stream_Write(s, "abcd", 4);
968 const size_t length = Stream_GetPosition(s);
969 wire[0] = (BYTE)((7 << 5) | (V3_TYPE_STANDARD << 1));
970 const BYTE eighth = wire[7];
971 wire[7] = wire[0];
972 wire[0] = eighth;
973 return rdpudp_receive(udp, wire, length);
974}
975
976/* Data packet where AckOfAcks equals its own sequence number; the client will not resend
977 * anything below it. */
978static BOOL server_receive_data_aoa(rdpUdp* udp, UINT16 dataSeq, UINT16 channelSeq)
979{
980 return server_receive_data_with_aoa(udp, dataSeq, channelSeq, dataSeq);
981}
982
983/* Advance clock in 5ms steps, running timers after each step. */
984static BOOL server_run_timers(rdpUdp* udp, UINT32 waitMs)
985{
986 for (UINT32 x = 0; x < waitMs; x += 5)
987 {
988 g_serverTime += 5ULL * 1000000ULL;
989 if (!rdpudp_check(udp))
990 return FALSE;
991 }
992 return TRUE;
993}
994
995/* Version 3 SYN padded to MTU. */
996static void server_make_syn(BYTE syn[SYN_LENGTH])
997{
998 memset(syn, 0, SYN_LENGTH);
999 wStream sbuffer = WINPR_C_ARRAY_INIT;
1000 wStream* s = Stream_StaticInit(&sbuffer, syn, SYN_LENGTH);
1001 Stream_Write_UINT32_BE(s, 0xFFFFFFFF); /* Source acknowledgement number */
1002 Stream_Write_UINT16_BE(s, 64); /* Receive window size */
1003 Stream_Write_UINT16_BE(s, 0x0001 | 0x1000); /* Set RDPUDP_FLAG_SYN and RDPUDP_FLAG_SYNEX */
1004 Stream_Write_UINT32_BE(s, 1000); /* Initial sequence number */
1005 Stream_Write_UINT16_BE(s, SYN_LENGTH); /* Upstream Maximum Transmission Unit (MTU) */
1006 Stream_Write_UINT16_BE(s, SYN_LENGTH); /* Downstream MTU */
1007 Stream_Write_UINT16_BE(s, 0x0001); /* Set the RDPUDP_VERSION_INFO_VALID flag */
1008 Stream_Write_UINT16_BE(s, RDPUDP_PROTOCOL_VERSION_3);
1009}
1010
1011/* Server connection using the test clock that has accepted a version 3 SYN. */
1012static rdpUdp* server_accept(ServerSent* sent)
1013{
1014 rdpUdp* udp = rdpudp_new(WLog_Get(TAG), nullptr, server_on_receive, sent);
1015 if (!udp)
1016 return nullptr;
1017 rdpudp_set_clock(udp, server_clock, nullptr);
1018
1019 BYTE syn[1232];
1020 server_make_syn(syn);
1021 if (!rdpudp_accept(udp, server_on_send, sent, syn, sizeof(syn)))
1022 {
1023 rdpudp_free(udp);
1024 return nullptr;
1025 }
1026 return udp;
1027}
1028
1029/* mstsc closes the connection if it receives an ACK vector for a duplicate old packet. */
1030static BOOL server_does_not_report_a_packet_behind_its_window(void)
1031{
1032 BOOL rc = FALSE;
1033 ServerSent sent = WINPR_C_ARRAY_INIT;
1034 rdpUdp* udp = server_accept(&sent);
1035 if (!udp)
1036 return FALSE;
1037
1038 /* The client's first data packet contains its AckOfAcks. */
1039 if (!server_receive_data_aoa(udp, 100, 1))
1040 goto out;
1041 for (UINT16 x = 1; x < 3; x++)
1042 {
1043 if (!server_receive_data(udp, (UINT16)(100 + x), (UINT16)(1 + x)))
1044 goto out;
1045 }
1046 if (!server_run_timers(udp, 100) || !sent.hasAck || (sent.ack != 102) || sent.hasVector)
1047 goto out;
1048
1049 /* Duplicate already covered by cumulative ACK. */
1050 if (!server_receive_data(udp, 100, 1) || !server_run_timers(udp, 100) || sent.hasVector)
1051 goto out;
1052
1053 /* Real gap should still be reported. */
1054 if (!server_receive_data(udp, 104, 5) || !server_run_timers(udp, 100) || !sent.hasVector ||
1055 (sent.vectorBase != 103))
1056 goto out;
1057
1058 rc = TRUE;
1059out:
1060 rdpudp_free(udp);
1061 return rc;
1062}
1063
1064/* FreeRDP clients only include an AckOfAcks in the first data packet. If that packet is lost
1065 * or delayed, taking the base from a subsequent packet would place it below the window,
1066 * and the cumulative ACK would inform the client that it arrived. */
1067static BOOL server_takes_its_base_from_an_ackofacks(void)
1068{
1069 BOOL rc = FALSE;
1070 ServerSent sent = WINPR_C_ARRAY_INIT;
1071 rdpUdp* udp = server_accept(&sent);
1072 if (!udp)
1073 return FALSE;
1074
1075 /* The second packet arrives first; no acknowledgments should be sent. */
1076 if (!server_receive_data(udp, 101, 2) || !server_run_timers(udp, 100) || sent.hasAck ||
1077 sent.hasVector)
1078 goto out;
1079 /* Now receive the first packet, which contains the AckOfAcks. */
1080 if (!server_receive_data_aoa(udp, 102, 1) || !server_run_timers(udp, 100))
1081 goto out;
1082 /* The window base is now 102: packet 101 was ignored, and chunk 2 must be resent. */
1083 if (!sent.hasAck || (sent.ack != 102) || (sent.delivered != 1))
1084 goto out;
1085 rc = TRUE;
1086out:
1087 rdpudp_free(udp);
1088 return rc;
1089}
1090
1091/* Input chunks with channel sequence numbers from first to last, one per packet. */
1092static BOOL server_receive_chunks(rdpUdp* udp, UINT16* dataSeq, UINT16 first, UINT16 last)
1093{
1094 for (UINT16 channel = first; channel <= last; channel++)
1095 {
1096 if (!server_receive_data(udp, (*dataSeq)++, channel))
1097 return FALSE;
1098 }
1099 return TRUE;
1100}
1101
1102/* Buffer only a few chunks after a gap until the client proves its cookie to prevent memory
1103 * exhaustion by attackers who only know the cookie hash. */
1104static BOOL server_limits_buffered_chunks_until_verified(void)
1105{
1106 BOOL rc = FALSE;
1107 ServerSent unverified = WINPR_C_ARRAY_INIT;
1108 ServerSent verified = WINPR_C_ARRAY_INIT;
1109 rdpUdp* a = server_accept(&unverified);
1110 rdpUdp* b = server_accept(&verified);
1111 if (!a || !b)
1112 goto out;
1113 rdpudp_set_peer_verified(b);
1114
1115 /* Chunk 129 arrives first (128 ahead of expected) with the client's first AckOfAcks,
1116 * followed by chunks 1..128 to fill the gap. */
1117 UINT16 seqA = 101;
1118 UINT16 seqB = 101;
1119 if (!server_receive_data_aoa(a, 100, 129) || !server_receive_chunks(a, &seqA, 1, 128) ||
1120 !server_receive_data_aoa(b, 100, 129) || !server_receive_chunks(b, &seqB, 1, 128))
1121 goto out;
1122
1123 /* Unverified, chunk 129 is dropped and must be retransmitted. */
1124 rc = (unverified.delivered == 128) && (verified.delivered == 129);
1125out:
1126 rdpudp_free(a);
1127 rdpudp_free(b);
1128 return rc;
1129}
1130
1131/* SYN must be padded to MTU; shorter SYNs from spoofed sources could be used for
1132 * amplification attacks via the larger SYN+ACK response. */
1133static BOOL server_refuses_a_short_syn(void)
1134{
1135 ServerSent sent = WINPR_C_ARRAY_INIT;
1136 rdpUdp* udp = rdpudp_new(WLog_Get(TAG), nullptr, server_on_receive, &sent);
1137 if (!udp)
1138 return FALSE;
1139
1140 BYTE syn[1232];
1141 server_make_syn(syn);
1142 const BOOL refused = !rdpudp_accept(udp, server_on_send, &sent, syn, 64) &&
1143 !rdpudp_accept(udp, server_on_send, &sent, syn, sizeof(syn) - 1);
1144 BYTE hash[32] = WINPR_C_ARRAY_INIT;
1145 const BOOL noHash = !rdpudp_get_syn_cookie_hash(syn, 64, hash) &&
1146 rdpudp_get_syn_cookie_hash(syn, sizeof(syn), hash);
1147 rdpudp_free(udp);
1148 return refused && noHash && (sent.sends == 0);
1149}
1150
1151/* Input a cumulative ACK from the client. */
1152static BOOL server_receive_ack(rdpUdp* udp, UINT16 ack)
1153{
1154 BYTE wire[32] = WINPR_C_ARRAY_INIT;
1155 wStream sbuffer = WINPR_C_ARRAY_INIT;
1156 wStream* s = Stream_StaticInit(&sbuffer, wire, sizeof(wire));
1157 Stream_Seek(s, 1); /* Skip the prefix byte */
1158 Stream_Write_UINT16(s, (UINT16)(V3_ACK | (15u << 12)));
1159 Stream_Write_UINT16(s, ack); /* Sequence number */
1160 write_uint24(s, 0); /* Received timestamp */
1161 Stream_Write_UINT8(s, 0); /* The sendAckTimeGap field */
1162 Stream_Write_UINT8(s, 0); /* Number of delayed ACKs */
1163 const size_t length = Stream_GetPosition(s);
1164 wire[0] = (BYTE)((7 << 5) | (V3_TYPE_STANDARD << 1));
1165 const BYTE eighth = wire[7];
1166 wire[7] = wire[0];
1167 wire[0] = eighth;
1168 return rdpudp_receive(udp, wire, length);
1169}
1170
1171/* Client determines the server's sequence space start from the first AckOfAcks. If initial
1172 * data is lost, a later packet without AckOfAcks may be used as the start, causing the
1173 * client to ack lost packets. Thus, every data packet carries AckOfAcks until the client
1174 * sends an ACK. */
1175static BOOL server_repeats_ack_of_acks_until_the_first_ack(void)
1176{
1177 BOOL rc = FALSE;
1178 ServerSent sent = WINPR_C_ARRAY_INIT;
1179 rdpUdp* udp = server_accept(&sent);
1180 if (!udp)
1181 return FALSE;
1182
1183 for (size_t x = 0; x < 3; x++)
1184 {
1185 if (!rdpudp_send(udp, (const BYTE*)"abcd", 4))
1186 goto out;
1187 }
1188 if (!server_run_timers(udp, 5) || (sent.dataSends != 3) || (sent.aoaSends != 3))
1189 {
1190 (void)fprintf(stderr, "before the ACK: %" PRIuz " data, %" PRIuz " with AckOfAcks\n",
1191 sent.dataSends, sent.aoaSends);
1192 goto out;
1193 }
1194
1195 /* After the first ACK, AckOfAcks is only resent when the base moves. */
1196 if (!server_receive_ack(udp, 102))
1197 goto out;
1198 sent.dataSends = 0;
1199 sent.aoaSends = 0;
1200 for (size_t x = 0; x < 2; x++)
1201 {
1202 if (!rdpudp_send(udp, (const BYTE*)"efgh", 4))
1203 goto out;
1204 }
1205 if (!server_run_timers(udp, 5))
1206 goto out;
1207 rc = (sent.dataSends == 2) && (sent.aoaSends == 1);
1208 if (!rc)
1209 (void)fprintf(stderr, "after the ACK: %" PRIuz " data, %" PRIuz " with AckOfAcks\n",
1210 sent.dataSends, sent.aoaSends);
1211out:
1212 rdpudp_free(udp);
1213 return rc;
1214}
1215
1216/* An ACK past the last datagram the server sent can only be forged, e.g. by someone who saw
1217 * the cookie hash in the SYN and spoofs the client's address. It must not acknowledge
1218 * anything, so the data is still resent after the retransmit timeout. */
1219static BOOL server_ignores_an_ack_past_what_it_sent(void)
1220{
1221 BOOL rc = FALSE;
1222 ServerSent sent = WINPR_C_ARRAY_INIT;
1223 rdpUdp* udp = server_accept(&sent);
1224 if (!udp)
1225 return FALSE;
1226
1227 for (size_t x = 0; x < 3; x++)
1228 {
1229 if (!rdpudp_send(udp, (const BYTE*)"abcd", 4))
1230 goto out;
1231 }
1232 if (!server_run_timers(udp, 5) || (sent.dataSends != 3))
1233 goto out;
1234
1235 /* data sequence numbers 100 to 102 are out; 0x2000 is far past them */
1236 if (!server_receive_ack(udp, 0x2000))
1237 goto out;
1238 sent.dataSends = 0;
1239 if (!server_run_timers(udp, 1500))
1240 goto out;
1241 rc = (sent.dataSends >= 1);
1242 if (!rc)
1243 (void)fprintf(stderr, "a forged ACK stopped the resends\n");
1244out:
1245 rdpudp_free(udp);
1246 return rc;
1247}
1248
1249/* A FreeRDP client that loses track of server sequence numbers after a silence may report a
1250 * packet in an ACK vector that only looks behind its window. The base is not the first
1251 * missing packet, meaning data below it was not received. */
1252static BOOL server_keeps_what_lies_below_a_behind_report(void)
1253{
1254 BOOL rc = FALSE;
1255 ServerSent sent = WINPR_C_ARRAY_INIT;
1256 rdpUdp* udp = server_accept(&sent);
1257 if (!udp)
1258 return FALSE;
1259
1260 for (size_t x = 0; x < 3; x++)
1261 {
1262 if (!rdpudp_send(udp, (const BYTE*)"abcd", 4))
1263 goto out;
1264 }
1265 if (!server_run_timers(udp, 5) || (sent.dataSends != 3))
1266 goto out;
1267
1268 /* ACK vector with base 101 reporting 101 as received; packet 100 remains unacknowledged. */
1269 BYTE wire[32] = WINPR_C_ARRAY_INIT;
1270 wStream sbuffer = WINPR_C_ARRAY_INIT;
1271 wStream* s = Stream_StaticInit(&sbuffer, wire, sizeof(wire));
1272 Stream_Seek(s, 1); /* Advance the stream pointer past the prefix byte */
1273 Stream_Write_UINT16(s, (UINT16)(V3_ACKVEC | (15u << 12)));
1274 Stream_Write_UINT16(s, 101); /* Set the base sequence number */
1275 Stream_Write_UINT8(s, 1); /* No timestamp; codedAckVecSize is 1 */
1276 Stream_Write_UINT8(s, 0x80 | 0x40 | 1); /* Indicates a run of one received packet */
1277 /* The prefix stores the length; 6 bytes follow it, and the datagram is padded to 8 bytes. */
1278 const size_t layout = Stream_GetPosition(s) - 1;
1279 const size_t length = 8;
1280 wire[0] = (BYTE)((layout << 5) | (V3_TYPE_STANDARD << 1));
1281 const BYTE eighth = wire[7];
1282 wire[7] = wire[0];
1283 wire[0] = eighth;
1284 if (!rdpudp_receive(udp, wire, length))
1285 goto out;
1286
1287 /* Chunk 1 was sent in packet 100; it remains unacknowledged and should be resent. */
1288 sent.watchedChannel = 1;
1289 sent.watchedSends = 0;
1290 if (!server_run_timers(udp, 1500))
1291 goto out;
1292 rc = (sent.watchedSends >= 1);
1293 if (!rc)
1294 (void)fprintf(stderr, "the behind report acknowledged datagram 100\n");
1295out:
1296 rdpudp_free(udp);
1297 return rc;
1298}
1299
1300/* First datagram after SYN+ACK provides the initial RTT sample. */
1301static rdpUdp* server_accept_with_rtt(ServerSent* sent, UINT32 rttMs)
1302{
1303 rdpUdp* udp = server_accept(sent);
1304 if (!udp)
1305 return nullptr;
1306 g_serverTime += 1000000ULL * rttMs;
1307 if (!server_receive_data(udp, 100, 1) || (rdpudp_get_rtt(udp) != rttMs))
1308 {
1309 (void)fprintf(stderr, "round trip %" PRIu32 " ms after the handshake\n",
1310 rdpudp_get_rtt(udp));
1311 rdpudp_free(udp);
1312 return nullptr;
1313 }
1314 return udp;
1315}
1316
1317/* The client never retransmits acked chunks; chunks too large to buffer must not be acked to
1318 * ensure the connection continues. */
1319static BOOL server_drops_an_oversized_chunk(void)
1320{
1321 BOOL rc = FALSE;
1322 ServerSent sent = WINPR_C_ARRAY_INIT;
1323 rdpUdp* udp = server_accept(&sent);
1324 if (!udp)
1325 return FALSE;
1326
1327 BYTE wire[2100] = WINPR_C_ARRAY_INIT;
1328 wStream sbuffer = WINPR_C_ARRAY_INIT;
1329 wStream* s = Stream_StaticInit(&sbuffer, wire, sizeof(wire));
1330 Stream_Seek(s, 1); /* Skip prefix byte */
1331 Stream_Write_UINT16(s, (UINT16)(V3_DATA | V3_AOA | (15u << 12)));
1332 Stream_Write_UINT16(s, 100); /* AckOfAcks, as on a client's first data packet */
1333 Stream_Write_UINT16(s, 100); /* Data sequence number. */
1334 Stream_Write_UINT16(s, 1); /* Write the channel sequence number. */
1335 Stream_Seek(s, 2049);
1336 const size_t length = Stream_GetPosition(s);
1337 wire[0] = (BYTE)((7 << 5) | (V3_TYPE_STANDARD << 1));
1338 const BYTE eighth = wire[7];
1339 wire[7] = wire[0];
1340 wire[0] = eighth;
1341 /* Server may send other ACKs, but none covering the dropped packet. */
1342 const BOOL dropped = rdpudp_receive(udp, wire, length) && server_run_timers(udp, 100) &&
1343 (!sent.hasAck || (sent.ack != 100)) && (sent.delivered == 0);
1344 const BOOL resent = server_receive_data_aoa(udp, 100, 1) && server_run_timers(udp, 100) &&
1345 (sent.delivered == 1);
1346 rc = dropped && resent && sent.hasAck && (sent.ack == 100);
1347 if (!rc)
1348 (void)fprintf(stderr,
1349 "dropped %d, resent %d, ack %d of 0x%04" PRIx16 ", %" PRIuz " delivered\n",
1350 dropped, resent, sent.hasAck, sent.ack, sent.delivered);
1351 rdpudp_free(udp);
1352 return rc;
1353}
1354
1355/* The initial RTT sample is provided by the first datagram received after the SYN+ACK. */
1356static BOOL server_samples_the_rtt_from_the_handshake(void)
1357{
1358 ServerSent sent = WINPR_C_ARRAY_INIT;
1359 rdpUdp* udp = server_accept_with_rtt(&sent, 120);
1360 if (!udp)
1361 return FALSE;
1362 rdpudp_free(udp);
1363 return TRUE;
1364}
1365
1366/* AckOfAcks can advance the window significantly in one datagram. The server must clear skipped
1367 * slots as ranges, even when wrapping around the slot arrays. */
1368static BOOL server_follows_large_ack_of_acks_jumps(void)
1369{
1370 BOOL rc = FALSE;
1371 ServerSent sent = WINPR_C_ARRAY_INIT;
1372 rdpUdp* udp = server_accept(&sent);
1373 if (!udp)
1374 return FALSE;
1375
1376 /* Sequence: 100, 30100 (no wrap), 50100 (wrap), each followed by the next sequence number. */
1377 const UINT16 seqs[] = { 100, 101, 30100, 30101, 50100, 50101 };
1378 for (size_t x = 0; x < ARRAYSIZE(seqs); x++)
1379 {
1380 const UINT16 channel = (UINT16)(1 + x);
1381 const BOOL ok = (x % 2 == 0) ? server_receive_data_aoa(udp, seqs[x], channel)
1382 : server_receive_data(udp, seqs[x], channel);
1383 if (!ok)
1384 goto out;
1385 }
1386 if (!server_run_timers(udp, 100))
1387 goto out;
1388 rc = (sent.delivered == ARRAYSIZE(seqs)) && sent.hasAck && (sent.ack == 50101) &&
1389 !sent.hasVector;
1390out:
1391 rdpudp_free(udp);
1392 return rc;
1393}
1394
1395/* A packet arriving ahead of a gap and skipped by an AckOfAcks must remain missing when the
1396 * 16-bit sequence number wraps around 65536 later. Receive slots are not cleared as the
1397 * window moves; they only track the specific sequence number they were stamped with. */
1398static BOOL server_does_not_find_a_skipped_slot_a_wrap_later(void)
1399{
1400 BOOL rc = FALSE;
1401 ServerSent sent = WINPR_C_ARRAY_INIT;
1402 rdpUdp* udp = server_accept(&sent);
1403 if (!udp)
1404 return FALSE;
1405
1406 /* Base 100; packet 105 arrives ahead of a gap, and an AckOfAcks at 110 skips past it. */
1407 if (!server_receive_data_aoa(udp, 100, 1) || !server_receive_data(udp, 105, 2) ||
1408 !server_receive_data_aoa(udp, 110, 3))
1409 goto out;
1410 /* Wrap the sequence space to 104; the window then waits for 105 again. */
1411 if (!server_receive_data_aoa(udp, 30110, 4) || !server_receive_data_aoa(udp, 60110, 5) ||
1412 !server_receive_data_aoa(udp, 104, 6) || !server_run_timers(udp, 100))
1413 goto out;
1414 sent.hasAck = FALSE;
1415 sent.hasVector = FALSE;
1416 /* Packet 106 arrives: 105 is missing, so it is reported in an ACK vector and not
1417 * acknowledged. */
1418 if (!server_receive_data(udp, 106, 7) || !server_run_timers(udp, 100))
1419 goto out;
1420 rc = sent.hasVector && (sent.vectorBase == 105) && !(sent.hasAck && (sent.ack == 106));
1421out:
1422 rdpudp_free(udp);
1423 return rc;
1424}
1425
1426/* ACKs were lost during silence, and the client's subsequent AckOfAcks is behind our
1427 * window. Since the sequence numbers did not wrap, the window remains in place and
1428 * acknowledging resumes. Moving the window back would report packets already covered
1429 * by a cumulative ACK (which causes mstsc to disconnect), while waiting for another
1430 * AckOfAcks would leave the client without ACKs indefinitely. */
1431static BOOL server_keeps_its_window_when_acks_were_lost_in_a_silence(void)
1432{
1433 BOOL rc = FALSE;
1434 ServerSent sent = WINPR_C_ARRAY_INIT;
1435 rdpUdp* udp = server_accept(&sent);
1436 if (!udp)
1437 return FALSE;
1438
1439 if (!server_receive_data_aoa(udp, 100, 1) || !server_receive_data(udp, 101, 2) ||
1440 !server_receive_data(udp, 102, 3) || !server_run_timers(udp, 100) || !sent.hasAck ||
1441 (sent.ack != 102))
1442 goto out;
1443
1444 /* Simulate a silence long enough for resynchronization, but short of the peer timeout. */
1445 if (!server_run_timers(udp, 9000))
1446 goto out;
1447 sent.hasAck = FALSE;
1448 sent.hasVector = FALSE;
1449
1450 /* The client did not receive our ACKs; packet 100 remains its oldest unacknowledged
1451 * packet. */
1452 if (!server_receive_data_with_aoa(udp, 103, 4, 100) || !server_run_timers(udp, 100))
1453 goto out;
1454 rc = sent.hasAck && (sent.ack == 103) && !sent.hasVector && (sent.delivered == 4);
1455 if (!rc)
1456 (void)fprintf(stderr,
1457 "after the silence: ACK %d of 0x%04" PRIx16 ", vector %d, %" PRIuz
1458 " delivered\n",
1459 sent.hasAck, sent.ack, sent.hasVector, sent.delivered);
1460out:
1461 rdpudp_free(udp);
1462 return rc;
1463}
1464
1465/* A test client that receives datagrams after a round-trip time (rttMs, based on packets
1466 * in flight at the time of sending) and acknowledges them in order. The application
1467 * keeps 256 chunks queued behind the window. The simulation runs for ms milliseconds
1468 * in 5 ms steps; *window is the maximum send window size during the final second. */
1469typedef UINT32 (*ServerRttFn)(UINT32 inFlight);
1470
1471static BOOL server_run_paced(rdpUdp* udp, ServerSent* sent, ServerRttFn rttMs, UINT32 ms,
1472 UINT64 due[65536], UINT16* nextSeq, UINT16* acked, size_t* window)
1473{
1474 *window = 0;
1475 for (UINT32 t = 0; t < ms; t += 5)
1476 {
1477 while (rdpudp_get_send_backlog(udp) < 256)
1478 {
1479 if (!rdpudp_send(udp, (const BYTE*)"abcd", 4))
1480 return FALSE;
1481 }
1482 g_serverTime += 5ULL * 1000000ULL;
1483 if (!rdpudp_check(udp))
1484 return FALSE;
1485 /* Record when the client receives the datagrams sent in this step */
1486 while (sent->hasDataSeq && (UINT16)(sent->lastDataSeq + 1 - *nextSeq) != 0 &&
1487 (UINT16)(sent->lastDataSeq - *nextSeq) < 0x8000)
1488 {
1489 const UINT32 inFlight = (UINT16)(*nextSeq - *acked);
1490 due[*nextSeq] = g_serverTime + 1000000ULL * rttMs(inFlight);
1491 (*nextSeq)++;
1492 }
1493 /* Acknowledge received datagrams in sequence. */
1494 UINT16 ack = *acked;
1495 while ((ack != *nextSeq) && (due[ack] <= g_serverTime))
1496 ack++;
1497 if (ack != *acked)
1498 {
1499 *acked = ack;
1500 if (!server_receive_ack(udp, (UINT16)(ack - 1)))
1501 return FALSE;
1502 }
1503 if ((ms - t <= 1000) && (rdpudp_get_send_window(udp) > *window))
1504 *window = rdpudp_get_send_window(udp);
1505 }
1506 return TRUE;
1507}
1508
1509static UINT32 rtt_2ms(WINPR_ATTR_UNUSED UINT32 inFlight)
1510{
1511 return 2;
1512}
1513
1514static UINT32 rtt_100ms(WINPR_ATTR_UNUSED UINT32 inFlight)
1515{
1516 return 100;
1517}
1518
1519/* Simulates a bottleneck queue: 2 ms base delay plus 0.1 ms per datagram in flight. */
1520static UINT32 rtt_queue(UINT32 inFlight)
1521{
1522 return 2 + inFlight / 10;
1523}
1524
1525/* The same queuing delay, but on a path with a 100 ms base delay */
1526static UINT32 rtt_queue_100ms(UINT32 inFlight)
1527{
1528 return 100 + inFlight / 10;
1529}
1530
1531/* The path delay increases from 2 ms to 100 ms mid-session (e.g., new route, VPN, handover).
1532 * Since reducing the window doesn't lower the RTT, this should be treated as the new base
1533 * delay. This allows the window to regrow rather than staying restricted for 10-20s until
1534 * the 1 ms minimum expires, which previously caused video to nearly stop in mstsc. */
1535static BOOL server_takes_a_lasting_delay_step_as_the_new_base(void)
1536{
1537 BOOL rc = FALSE;
1538 ServerSent sent = WINPR_C_ARRAY_INIT;
1539 static UINT64 due[65536];
1540 UINT16 nextSeq = 100;
1541 UINT16 acked = 100;
1542 size_t before = 0;
1543 size_t after = 0;
1544 rdpUdp* udp = server_accept(&sent);
1545 if (!udp)
1546 return FALSE;
1547 if (!server_receive_data_aoa(udp, 100, 1) ||
1548 !server_run_paced(udp, &sent, rtt_2ms, 3000, due, &nextSeq, &acked, &before) ||
1549 !server_run_paced(udp, &sent, rtt_100ms, 3000, due, &nextSeq, &acked, &after))
1550 goto out;
1551 rc = (before >= 1000) && (after * 2 >= before);
1552 if (!rc)
1553 (void)fprintf(stderr, "send window %" PRIuz " before the delay step, %" PRIuz " after\n",
1554 before, after);
1555out:
1556 rdpudp_free(udp);
1557 return rc;
1558}
1559
1560/* A queue built by the sender drains when the window is cut, reducing the round trip time
1561 * and keeping the window limited by the delay. This persists because if the minimum RTT
1562 * were updated to the lowest sample of the last few seconds, the standing queue would be
1563 * mistaken for the base delay, allowing the window to grow by the allowance. */
1564static BOOL server_keeps_cutting_for_its_own_queue(void)
1565{
1566 BOOL rc = FALSE;
1567 ServerSent sent = WINPR_C_ARRAY_INIT;
1568 static UINT64 due[65536];
1569 UINT16 nextSeq = 100;
1570 UINT16 acked = 100;
1571 size_t window = 0;
1572 rdpUdp* udp = server_accept(&sent);
1573 if (!udp)
1574 return FALSE;
1575 if (!server_receive_data_aoa(udp, 100, 1) ||
1576 !server_run_paced(udp, &sent, rtt_queue, 45000, due, &nextSeq, &acked, &window))
1577 goto out;
1578 /* 1000 in-flight packets would be 102 ms, far exceeding the 2 ms base plus 30 ms allowance */
1579 rc = (window < 1000);
1580 if (!rc)
1581 (void)fprintf(stderr, "send window %" PRIuz " with a queue of its own\n", window);
1582out:
1583 rdpudp_free(udp);
1584 return rc;
1585}
1586
1587/* The path delay drops from 100ms to 2ms while the sender maintains its own queue, so no
1588 * sample reflects the new delay and the minimum remains at 100ms; the queue fills the gap
1589 * left by the path. The drain probe finds the new minimum, reducing the round trip time. */
1590static BOOL server_follows_the_base_delay_down(void)
1591{
1592 BOOL rc = FALSE;
1593 ServerSent sent = WINPR_C_ARRAY_INIT;
1594 static UINT64 due[65536];
1595 UINT16 nextSeq = 100;
1596 UINT16 acked = 100;
1597 size_t window = 0;
1598 rdpUdp* udp = server_accept(&sent);
1599 if (!udp)
1600 return FALSE;
1601 /* Simulate the 100 ms delay incurred during the handshake. */
1602 g_serverTime += 100ULL * 1000000ULL;
1603 if (!server_receive_data_aoa(udp, 100, 1) ||
1604 !server_run_paced(udp, &sent, rtt_queue_100ms, 5000, due, &nextSeq, &acked, &window) ||
1605 !server_run_paced(udp, &sent, rtt_queue, 30000, due, &nextSeq, &acked, &window))
1606 goto out;
1607 /* 2 ms base delay plus a 30 ms allowance, and some growth (35 ms with the probe,
1608 * 60 ms without). */
1609 rc = (rdpudp_get_rtt(udp) < 48);
1610 if (!rc)
1611 (void)fprintf(stderr, "round trip %" PRIu32 " ms after the delay fell to 2 ms\n",
1612 rdpudp_get_rtt(udp));
1613out:
1614 rdpudp_free(udp);
1615 return rc;
1616}
1617
1618/* mstsc sends a keepalive a little over every 4 seconds (4.01 to 4.02 in a capture). After
1619 * three lost ones the fourth arrives 16.06 seconds after the last one heard: the tunnel has to
1620 * be there for it still, as it is on Windows, which waits 16.5 seconds. */
1621static BOOL server_waits_for_the_fourth_keepalive(void)
1622{
1623 BOOL rc = FALSE;
1624 ServerSent sent = WINPR_C_ARRAY_INIT;
1625 rdpUdp* udp = server_accept(&sent);
1626 if (!udp)
1627 return FALSE;
1628
1629 if (!server_receive_data_aoa(udp, 100, 1) || !server_run_timers(udp, 16060))
1630 goto out;
1631 sent.hasAck = FALSE;
1632 if (!server_receive_data_aoa(udp, 101, 2) || !server_run_timers(udp, 100))
1633 goto out;
1634 rc = (rdpudp_get_state(udp) == RDPUDP_STATE_ESTABLISHED) && sent.hasAck && (sent.ack == 101) &&
1635 (sent.delivered == 2);
1636out:
1637 rdpudp_free(udp);
1638 return rc;
1639}
1640
1641/* Silent clients are dropped after the peer timeout. */
1642static BOOL server_ends_a_silent_connection(void)
1643{
1644 BOOL rc = FALSE;
1645 ServerSent sent = WINPR_C_ARRAY_INIT;
1646 rdpUdp* udp = server_accept(&sent);
1647 if (!udp)
1648 return FALSE;
1649
1650 if (!server_run_timers(udp, 5000))
1651 goto out;
1652 for (size_t x = 0; x < 60; x++)
1653 {
1654 g_serverTime += 1000ULL * 1000000ULL;
1655 if (!rdpudp_check(udp))
1656 {
1657 rc = rdpudp_get_state(udp) == RDPUDP_STATE_FAILED;
1658 break;
1659 }
1660 }
1661out:
1662 rdpudp_free(udp);
1663 return rc;
1664}
1665
1666/* A receiver that cannot take more holds data back: packets are dropped unacknowledged while
1667 * the hold is on, and taken when the client sends them again after it. */
1668static BOOL server_takes_no_data_while_held(void)
1669{
1670 BOOL rc = FALSE;
1671 ServerSent sent = WINPR_C_ARRAY_INIT;
1672 rdpUdp* udp = server_accept(&sent);
1673 if (!udp)
1674 return FALSE;
1675
1676 if (!server_receive_data_aoa(udp, 100, 1) || !server_run_timers(udp, 100) || !sent.hasAck ||
1677 (sent.ack != 100) || (sent.delivered != 1))
1678 goto out;
1679
1680 rdpudp_set_receive_hold(udp, TRUE);
1681 sent.hasAck = FALSE;
1682 if (!server_receive_data(udp, 101, 2) || !server_receive_data(udp, 102, 3) ||
1683 !server_receive_data(udp, 103, 4) || !server_run_timers(udp, 100))
1684 goto out;
1685 if (sent.hasAck || sent.hasVector || (sent.delivered != 1))
1686 {
1687 (void)fprintf(stderr, "held: ACK %d, vector %d, %" PRIuz " delivered\n", sent.hasAck,
1688 sent.hasVector, sent.delivered);
1689 goto out;
1690 }
1691
1692 rdpudp_set_receive_hold(udp, FALSE);
1693 if (!server_receive_data(udp, 101, 2) || !server_receive_data(udp, 102, 3) ||
1694 !server_receive_data(udp, 103, 4) || !server_run_timers(udp, 100))
1695 goto out;
1696 rc = sent.hasAck && (sent.ack == 103) && !sent.hasVector && (sent.delivered == 4);
1697 if (!rc)
1698 (void)fprintf(stderr, "released: ACK %d of 0x%04" PRIx16 ", %" PRIuz " delivered\n",
1699 sent.hasAck, sent.ack, sent.delivered);
1700out:
1701 rdpudp_free(udp);
1702 return rc;
1703}
1704
1705/* After a silence the server holds its ACKs back until an AckOfAcks comes. Its keepalive goes
1706 * on: an AckOfAcks of its own, which acknowledges nothing. */
1707static BOOL server_keepalive_after_a_silence_is_an_ack_of_acks(void)
1708{
1709 BOOL rc = FALSE;
1710 ServerSent sent = WINPR_C_ARRAY_INIT;
1711 rdpUdp* udp = server_accept(&sent);
1712 if (!udp)
1713 return FALSE;
1714
1715 if (!server_receive_data_aoa(udp, 100, 1) || !server_run_timers(udp, 100) || !sent.hasAck)
1716 goto out;
1717 /* idle, the keepalive is an ACK */
1718 sent.hasAck = FALSE;
1719 if (!server_run_timers(udp, 4500) || !sent.hasAck || (sent.baseSends != 0))
1720 goto out;
1721
1722 /* 8 seconds without a datagram from the client */
1723 if (!server_run_timers(udp, 4000))
1724 goto out;
1725 sent.hasAck = FALSE;
1726 sent.hasVector = FALSE;
1727 const size_t before = sent.sends;
1728 const size_t baseBefore = sent.baseSends;
1729 if (!server_run_timers(udp, 4500))
1730 goto out;
1731 const size_t bases = sent.baseSends - baseBefore;
1732 rc = (bases >= 1) && (sent.sends == before + bases) && !sent.hasAck && !sent.hasVector;
1733 if (!rc)
1734 (void)fprintf(stderr, "after the silence: %" PRIuz " AckOfAcks, %" PRIuz " sent, ACK %d\n",
1735 bases, sent.sends - before, sent.hasAck);
1736out:
1737 rdpudp_free(udp);
1738 return rc;
1739}
1740
1741/* A FreeRDP client and a FreeRDP server joined through the test's socket, both on the test
1742 * clock. */
1743typedef struct
1744{
1745 TestCtx client;
1746 rdpUdp* server;
1747 ServerSent sent;
1748 size_t loseToClient; /* datagrams of the server still to lose */
1749 size_t loseToServer; /* datagrams of the client still to lose */
1750 size_t loseBases; /* AckOfAcks keepalives of the server still to lose */
1751} Pair;
1752
1753static BOOL pair_on_send(void* custom, const BYTE* data, size_t length)
1754{
1755 Pair* pair = custom;
1756 /* counts what the server sends, see ServerSent */
1757 const size_t bases = pair->sent.baseSends;
1758 if (!server_on_send(&pair->sent, data, length))
1759 return FALSE;
1760 if ((pair->sent.baseSends != bases) && (pair->loseBases > 0))
1761 {
1762 pair->loseBases--;
1763 return TRUE;
1764 }
1765 if (pair->loseToClient > 0)
1766 {
1767 pair->loseToClient--;
1768 return TRUE;
1769 }
1770 return server_send_raw(&pair->client, data, length);
1771}
1772
1773/* Moves the clock on in steps of 10 ms. FALSE when either end failed. */
1774static BOOL pair_run(Pair* pair, UINT32 ms)
1775{
1776 BYTE buffer[1500] = WINPR_C_ARRAY_INIT;
1777 for (UINT32 x = 0; x < ms; x += 10)
1778 {
1779 g_serverTime += 10ULL * 1000000ULL;
1780 if (!rdpudp_check(pair->client.udp))
1781 return FALSE;
1782 size_t length = 0;
1783 while ((length = server_recv(&pair->client, buffer, sizeof(buffer), 0)) > 0)
1784 {
1785 if (pair->loseToServer > 0)
1786 {
1787 pair->loseToServer--;
1788 continue;
1789 }
1790 if (!rdpudp_receive(pair->server, buffer, length))
1791 return FALSE;
1792 }
1793 if (!rdpudp_check(pair->server))
1794 return FALSE;
1795 }
1796 return TRUE;
1797}
1798
1799static void pair_free(Pair* pair)
1800{
1801 rdpudp_free(pair->server);
1802 pair->server = nullptr;
1803 ctx_free(&pair->client);
1804}
1805
1806/* Connected, with one chunk delivered each way, so both ends know the other's base. */
1807static BOOL pair_connect(Pair* pair)
1808{
1809 SynInfo syn = WINPR_C_ARRAY_INIT;
1810 if (!ctx_start(&pair->client, TRUE, &syn) || (syn.length > sizeof(syn.raw)))
1811 return FALSE;
1812 /* the test clock takes over from the system clock without going back */
1813 g_serverTime = GetTickCount64() * 1000000ULL;
1814 rdpudp_set_clock(pair->client.udp, server_clock, nullptr);
1815
1816 pair->server = rdpudp_new(WLog_Get(TAG), nullptr, server_on_receive, &pair->sent);
1817 if (!pair->server)
1818 return FALSE;
1819 rdpudp_set_clock(pair->server, server_clock, nullptr);
1820 if (!rdpudp_accept(pair->server, pair_on_send, pair, syn.raw, syn.length))
1821 return FALSE;
1822 for (size_t x = 0;
1823 (x < 100) && (rdpudp_get_state(pair->client.udp) != RDPUDP_STATE_ESTABLISHED); x++)
1824 {
1825 if (!pump(&pair->client))
1826 return FALSE;
1827 }
1828 if (rdpudp_get_state(pair->client.udp) != RDPUDP_STATE_ESTABLISHED)
1829 return FALSE;
1830
1831 if (!rdpudp_send(pair->client.udp, (const BYTE*)"c", 1) ||
1832 !rdpudp_send(pair->server, (const BYTE*)"s", 1))
1833 return FALSE;
1834 for (size_t x = 0; (x < 100) && ((pair->sent.delivered < 1) ||
1835 (Stream_GetPosition(pair->client.delivered) < 1));
1836 x++)
1837 {
1838 Sleep(1);
1839 if (!pair_run(pair, 10))
1840 return FALSE;
1841 }
1842 return (pair->sent.delivered == 1) && delivered_is(&pair->client, "s");
1843}
1844
1845/* An idle tunnel loses one keepalive: the end that misses it hears nothing for two keepalive
1846 * intervals and holds its ACKs back from then on. Without a keepalive from an end in that state
1847 * the other end went the same way 8 seconds later, and the peer timeout ended a tunnel whose
1848 * path had lost a single datagram. */
1849static BOOL idle_pair_survives(BOOL fromServer)
1850{
1851 BOOL rc = FALSE;
1852 Pair pair = WINPR_C_ARRAY_INIT;
1853 pair.client.server = INVALID_SOCKET;
1854 CHECK(pair_connect(&pair));
1855 CHECK(pair_run(&pair, 1000));
1856
1857 if (fromServer)
1858 pair.loseToClient = 1;
1859 else
1860 pair.loseToServer = 1;
1861 /* well past the 16 second peer timeout */
1862 CHECK(pair_run(&pair, 40000));
1863 CHECK((pair.loseToClient == 0) && (pair.loseToServer == 0));
1864
1865 /* and the stream goes on in both directions */
1866 CHECK(rdpudp_send(pair.client.udp, (const BYTE*)"d", 1));
1867 CHECK(rdpudp_send(pair.server, (const BYTE*)"t", 1));
1868 for (size_t x = 0; (x < 100) && ((pair.sent.delivered < 2) ||
1869 (Stream_GetPosition(pair.client.delivered) < 2));
1870 x++)
1871 {
1872 Sleep(1);
1873 CHECK(pair_run(&pair, 10));
1874 }
1875 CHECK(pair.sent.delivered == 2);
1876 CHECK(delivered_is(&pair.client, "st"));
1877 rc = TRUE;
1878fail:
1879 pair_free(&pair);
1880 return rc;
1881}
1882
1883/* Found with the Keepalive model: a client that missed one keepalive is in resync and sends
1884 * nothing, so the server hears nothing either and has to wake it with the AckOfAcks keepalive
1885 * before its own peer timeout. At the normal keepalive interval it gets two attempts; with both
1886 * lost, three lost datagrams in 16 seconds ended the tunnel. */
1887static BOOL idle_tunnel_survives_lost_wake_ups(void)
1888{
1889 BOOL rc = FALSE;
1890 Pair pair = WINPR_C_ARRAY_INIT;
1891 pair.client.server = INVALID_SOCKET;
1892 CHECK(pair_connect(&pair));
1893 CHECK(pair_run(&pair, 1000));
1894
1895 /* the client misses a keepalive and falls silent, then the server's first two wake-ups
1896 * are lost */
1897 pair.loseToClient = 1;
1898 pair.loseBases = 2;
1899 CHECK(pair_run(&pair, 40000));
1900 CHECK((pair.loseToClient == 0) && (pair.loseBases == 0));
1901 rc = TRUE;
1902fail:
1903 pair_free(&pair);
1904 return rc;
1905}
1906
1907static BOOL idle_tunnel_survives_a_lost_server_keepalive(void)
1908{
1909 return idle_pair_survives(TRUE);
1910}
1911
1912static BOOL idle_tunnel_survives_a_lost_client_keepalive(void)
1913{
1914 return idle_pair_survives(FALSE);
1915}
1916
1917/* A burst of timeouts should double the RTO only once, not once per datagram (up to 64x),
1918 * to avoid leaving the tunnel silent for seconds. */
1919static BOOL server_backs_off_once_for_many_timeouts(void)
1920{
1921 BOOL rc = FALSE;
1922 ServerSent sent = WINPR_C_ARRAY_INIT;
1923 rdpUdp* udp = server_accept(&sent);
1924 if (!udp)
1925 return FALSE;
1926
1927 /* Eight unacked datagrams time out simultaneously. */
1928 for (size_t x = 0; x < 8; x++)
1929 {
1930 if (!rdpudp_send(udp, (const BYTE*)"abcd", 4))
1931 goto out;
1932 }
1933 if (!server_run_timers(udp, 250))
1934 goto out;
1935
1936 /* RTO should only double once, ensuring the next datagram is retransmitted within a few hundred
1937 * ms. */
1938 sent.watchedChannel = (UINT16)(sent.lastChannel + 1);
1939 sent.watchedSends = 0;
1940 if (!rdpudp_send(udp, (const BYTE*)"efgh", 4) || !server_run_timers(udp, 700))
1941 goto out;
1942 rc = sent.watchedSends >= 2;
1943out:
1944 rdpudp_free(udp);
1945 return rc;
1946}
1947
1948/* A client resends a datagram that is never acknowledged at least every 2 seconds. Doubling up
1949 * to 120 seconds, a chunk lost five times in a row came back after the server had waited 16
1950 * seconds for it and ended the stream; at 20% loss that happened in a few percent of tunnels. */
1951static BOOL client_resends_at_least_every_two_seconds(void)
1952{
1953 BOOL rc = FALSE;
1954 TestCtx ctx = WINPR_C_ARRAY_INIT;
1955 SynInfo syn = WINPR_C_ARRAY_INIT;
1956 CHECK(ctx_start(&ctx, TRUE, &syn));
1957 /* the test clock takes over from the system clock without going back */
1958 g_serverTime = GetTickCount64() * 1000000ULL;
1959 rdpudp_set_clock(ctx.udp, server_clock, nullptr);
1960 CHECK(send_syn_ack(&ctx, syn.initialSequence, RDPUDP_PROTOCOL_VERSION_3));
1961 for (size_t x = 0; (x < 100) && (rdpudp_get_state(ctx.udp) != RDPUDP_STATE_ESTABLISHED); x++)
1962 CHECK(pump(&ctx));
1963 CHECK(rdpudp_get_state(ctx.udp) == RDPUDP_STATE_ESTABLISHED);
1964
1965 CHECK(rdpudp_send(ctx.udp, (const BYTE*)"x", 1));
1966 CHECK(drain(&ctx, 20));
1967 CHECK(count_data(&ctx) == 1);
1968
1969 /* 12 seconds without an acknowledgement, short of the 16 second peer timeout */
1970 UINT64 lastSend = g_serverTime;
1971 UINT64 longestGap = 0;
1972 size_t resends = 0;
1973 for (size_t step = 0; step < 1200; step++)
1974 {
1975 g_serverTime += 10ULL * 1000000ULL;
1976 CHECK(rdpudp_check(ctx.udp));
1977 CHECK(drain(&ctx, 0));
1978 if (count_data(&ctx) == 0)
1979 continue;
1980 const UINT64 gap = g_serverTime - lastSend;
1981 if (gap > longestGap)
1982 longestGap = gap;
1983 lastSend = g_serverTime;
1984 resends++;
1985 }
1986 CHECK(resends >= 6);
1987 CHECK(longestGap <= 2000ULL * 1000000ULL);
1988 CHECK(g_serverTime - lastSend <= 2000ULL * 1000000ULL);
1989 rc = TRUE;
1990fail:
1991 ctx_free(&ctx);
1992 return rc;
1993}
1994
1995/* A data packet of ours carries a cumulative ACK when one is pending. While a packet behind the
1996 * window waits for its ACK vector, that ACK would take the vector's place, and nothing would send
1997 * the vector until the next standalone ACK. */
1998static BOOL ack_vector_is_not_lost_to_outgoing_data(void)
1999{
2000 BOOL rc = FALSE;
2001 TestCtx ctx = WINPR_C_ARRAY_INIT;
2002 CHECK(ctx_connect(&ctx));
2003 /* the peer lets our acknowledgements wait 200 ms */
2004 const V3Out first = { .hasDelayAck = TRUE,
2005 .maxDelayedAcks = 8,
2006 .delayedAckTimeout = 200,
2007 .hasData = TRUE,
2008 .dataSeq = 100,
2009 .channelSeq = 1,
2010 .payload = (const BYTE*)"first",
2011 .payloadLength = 5 };
2012 CHECK(server_send_v3(&ctx, &first));
2013 CHECK(pump(&ctx));
2014 Sleep(250);
2015 CHECK(pump(&ctx));
2016 CHECK(drain(&ctx, 20));
2017 CHECK(last_ack(&ctx));
2018
2019 /* the peer resends it, behind the window now, and our data goes out before its ACK is due */
2020 CHECK(send_data(&ctx, 100, 1, "first"));
2021 CHECK(pump(&ctx));
2022 CHECK(rdpudp_send(ctx.udp, (const BYTE*)"x", 1));
2023 CHECK(drain(&ctx, 20));
2024 const V3Packet* sent = first_data(&ctx);
2025 CHECK(sent && !(sent->flags & V3_ACK));
2026
2027 /* once due, the resent packet is acknowledged on its own */
2028 Sleep(250);
2029 CHECK(pump(&ctx));
2030 CHECK(drain(&ctx, 20));
2031 BOOL vector = FALSE;
2032 for (size_t x = 0; x < ctx.seenCount; x++)
2033 {
2034 const V3Packet* p = &ctx.seen[x];
2035 if ((p->flags & V3_ACKVEC) && (p->vecBase == 100) && (p->vecLength == 1) &&
2036 (p->vec[0] == (0x80 | 0x40 | 1)))
2037 vector = TRUE;
2038 }
2039 CHECK(vector);
2040 CHECK(delivered_is(&ctx, "first"));
2041 rc = TRUE;
2042fail:
2043 ctx_free(&ctx);
2044 return rc;
2045}
2046
2047/* A resend under a new data sequence number repeats a channel sequence already handed up.
2048 * Delivering it again duplicates bytes in the stream. */
2049static BOOL retransmitted_channel_data_is_not_delivered_twice(void)
2050{
2051 BOOL rc = FALSE;
2052 TestCtx ctx = WINPR_C_ARRAY_INIT;
2053 CHECK(ctx_connect(&ctx));
2054 CHECK(send_data(&ctx, 100, 1, "a"));
2055 CHECK(send_data(&ctx, 101, 2, "b"));
2056 CHECK(send_data(&ctx, 102, 2, "b"));
2057 CHECK(send_data(&ctx, 103, 3, "c"));
2058 CHECK(pump(&ctx));
2059 CHECK(delivered_is(&ctx, "abc"));
2060 rc = TRUE;
2061fail:
2062 ctx_free(&ctx);
2063 return rc;
2064}
2065
2066static BOOL gap_produces_an_ack_vector_rather_than_a_cumulative_ack(void)
2067{
2068 BOOL rc = FALSE;
2069 TestCtx ctx = WINPR_C_ARRAY_INIT;
2070 CHECK(ctx_connect(&ctx));
2071 CHECK(send_data(&ctx, 100, 1, "a"));
2072 CHECK(send_data(&ctx, 102, 3, "c"));
2073 CHECK(pump(&ctx));
2074 CHECK(drain(&ctx, 20));
2075 const V3Packet* ack = last_ack(&ctx);
2076 CHECK(ack);
2077 CHECK((ack->flags & V3_ACKVEC) && !(ack->flags & V3_ACK));
2078 CHECK(ack->vecBase == 101);
2079 /* bit 0 is the base (101, missing), bit 1 is 102 (received) */
2080 CHECK((ack->vecLength == 1) && (ack->vec[0] == 0x02));
2081 rc = TRUE;
2082fail:
2083 ctx_free(&ctx);
2084 return rc;
2085}
2086
2087static BOOL ack_advertises_the_largest_window(void)
2088{
2089 BOOL rc = FALSE;
2090 TestCtx ctx = WINPR_C_ARRAY_INIT;
2091 CHECK(ctx_connect(&ctx));
2092 CHECK(send_data(&ctx, 100, 1, "a"));
2093 CHECK(pump(&ctx));
2094 CHECK(drain(&ctx, 20));
2095 const V3Packet* ack = last_ack(&ctx);
2096 CHECK(ack && (ack->flags & V3_ACK) && (ack->ack == 100));
2097 /* Windows always advertises 2^15 * MTU, a smaller window throttles its sender */
2098 CHECK(ack->logWindow == 15);
2099 rc = TRUE;
2100fail:
2101 ctx_free(&ctx);
2102 return rc;
2103}
2104
2105/* Windows wraps the channel sequence 65535 -> 1, skipping 0. Waiting for a 0 the peer never sends
2106 * stalls the stream for good while the transport stays healthy. */
2107static BOOL channel_sequence_wraps_past_zero(void)
2108{
2109 BOOL rc = FALSE;
2110 TestCtx ctx = WINPR_C_ARRAY_INIT;
2111 CHECK(ctx_connect(&ctx));
2112 UINT16 dataSeq = FIRST_SEQUENCE;
2113 UINT16 channel = 1;
2114 CHECK(stream_ahead(&ctx, &dataSeq, &channel, 65534));
2115 CHECK(channel == 65535);
2116 const size_t before = Stream_GetPosition(ctx.delivered);
2117 CHECK(before == 65534);
2118
2119 CHECK(send_data(&ctx, dataSeq, 65535, "f"));
2120 CHECK(send_data(&ctx, (UINT16)(dataSeq + 1), 1, "a"));
2121 CHECK(pump(&ctx));
2122 CHECK(delivered_tail_is(&ctx, before, "fa"));
2123
2124 CHECK(send_data(&ctx, (UINT16)(dataSeq + 2), 2, "b"));
2125 CHECK(pump(&ctx));
2126 CHECK(delivered_tail_is(&ctx, before, "fab"));
2127 rc = TRUE;
2128fail:
2129 ctx_free(&ctx);
2130 return rc;
2131}
2132
2133/* A packet captured from Windows: an ACK with one delayed acknowledgement ahead of the data.
2134 * Reading numDelayedAcks from the wrong nibble shifts DataHeader and loses the payload. */
2135static BOOL real_server_ack_with_delayed_acks_and_data(void)
2136{
2137 static const BYTE raw[] = { 0x00, 0x45, 0xf0, 0x66, 0x00, 0x03, 0x22, 0xe0,
2138 0x00, 0x01, 0x54, 0x08, 0xe0, 0x00, 0x02, 0x00,
2139 0x17, 0x03, 0x03, 0x00, 0x62, 0x56, 0x2c, 0x9f };
2140 BOOL rc = FALSE;
2141 TestCtx ctx = WINPR_C_ARRAY_INIT;
2142 CHECK(ctx_connect(&ctx));
2143 /* the captured packet is data sequence 224 carrying channel sequence 2 */
2144 CHECK(send_data(&ctx, 223, 1, "a"));
2145 CHECK(server_send_raw(&ctx, raw, sizeof(raw)));
2146 CHECK(pump(&ctx));
2147 CHECK(Stream_GetPosition(ctx.delivered) > 6);
2148 CHECK(memcmp(Stream_Buffer(ctx.delivered), "a\x17\x03\x03\x00\x62", 6) == 0);
2149 rc = TRUE;
2150fail:
2151 ctx_free(&ctx);
2152 return rc;
2153}
2154
2155/* ---------------------------------------------------------------------------------------- */
2156/* Sending */
2157/* ---------------------------------------------------------------------------------------- */
2158
2159/* AckOfAcks is the lowest data sequence number still awaiting acknowledgement. Sending the
2160 * current sequence number would lead the peer to abandon all in-flight packets. Until the
2161 * peer acknowledges any packet, AoA is included in every data packet so the peer can
2162 * determine the start of the sequence space and detect lost initial packets
2163 * ([MS-RDPEUDP2] 3.1.5.3). Thereafter, it is only sent when the value changes. */
2164static BOOL ack_of_acks_reports_the_oldest_unacknowledged_packet(void)
2165{
2166 BOOL rc = FALSE;
2167 TestCtx ctx = WINPR_C_ARRAY_INIT;
2168 CHECK(ctx_connect(&ctx));
2169 CHECK(rdpudp_send(ctx.udp, (const BYTE*)"1", 1));
2170 CHECK(drain(&ctx, 20));
2171 const V3Packet* sent = first_data(&ctx);
2172 CHECK(sent && sent->hasAoA && (sent->aoa == FIRST_SEQUENCE));
2173
2174 /* Still unacknowledged: the AoA value is repeated. */
2175 CHECK(rdpudp_send(ctx.udp, (const BYTE*)"2", 1));
2176 CHECK(drain(&ctx, 20));
2177 sent = first_data(&ctx);
2178 CHECK(sent && sent->hasAoA && (sent->aoa == FIRST_SEQUENCE));
2179
2180 CHECK(send_ack(&ctx, FIRST_SEQUENCE));
2181 CHECK(pump(&ctx));
2182 CHECK(rdpudp_send(ctx.udp, (const BYTE*)"3", 1));
2183 CHECK(drain(&ctx, 20));
2184 sent = first_data(&ctx);
2185 CHECK(sent && sent->hasAoA && (sent->aoa == FIRST_SEQUENCE + 1));
2186
2187 /* Acknowledged and unchanged: AoA is omitted. */
2188 CHECK(rdpudp_send(ctx.udp, (const BYTE*)"4", 1));
2189 CHECK(drain(&ctx, 20));
2190 sent = first_data(&ctx);
2191 CHECK(sent && !sent->hasAoA);
2192 rc = TRUE;
2193fail:
2194 ctx_free(&ctx);
2195 return rc;
2196}
2197
2198/* Once the 16 bit data sequence wraps, a cumulative ACK has to be compared with serial
2199 * arithmetic: a plain comparison keeps every outstanding packet and resends them all. */
2200static BOOL acknowledgements_survive_sequence_wraparound(void)
2201{
2202 BOOL rc = FALSE;
2203 TestCtx ctx = WINPR_C_ARRAY_INIT;
2204 CHECK(ctx_connect(&ctx));
2205
2206 /* send and acknowledge until the next data sequence is 0xFFFE */
2207 UINT16 next = FIRST_SEQUENCE;
2208 while (next != 0xFFFE)
2209 {
2210 const size_t batch = ((size_t)(0xFFFE - next) > 64) ? 64 : (size_t)(0xFFFE - next);
2211 for (size_t x = 0; x < batch; x++)
2212 CHECK(rdpudp_send(ctx.udp, (const BYTE*)".", 1));
2213 CHECK(collect_data(&ctx, batch, 1000));
2214 next = (UINT16)(next + batch);
2215 CHECK(send_ack(&ctx, (UINT16)(next - 1)));
2216 CHECK(pump(&ctx));
2217 }
2218
2219 /* 0xFFFE, 0xFFFF, 0x0000 and 0x0001 go out, the peer acknowledges up to 0x0000 */
2220 for (size_t x = 0; x < 4; x++)
2221 CHECK(rdpudp_send(ctx.udp, (const BYTE*)"w", 1));
2222 CHECK(collect_data(&ctx, 4, 1000));
2223 CHECK(send_ack(&ctx, 0x0000));
2224 CHECK(pump(&ctx));
2225
2226 /* only 0x0001 is left to resend */
2227 Sleep(400);
2228 CHECK(pump(&ctx));
2229 CHECK(drain(&ctx, 20));
2230 CHECK(count_data(&ctx) == 1);
2231 const V3Packet* resent = first_data(&ctx);
2232 CHECK(resent && (resent->channelSeq == 0xFFFE - FIRST_SEQUENCE + 4));
2233 rc = TRUE;
2234fail:
2235 ctx_free(&ctx);
2236 return rc;
2237}
2238
2239/* After a silence the peer may come back more than half the sequence space ahead, Windows used
2240 * 45000 numbers in a 25 s outage. Its AckOfAcks has to become the base then: taking its numbers
2241 * for old ones, the client would acknowledge one the peer never sent. */
2242static BOOL ack_of_acks_resyncs_after_a_silence(void)
2243{
2244 BOOL rc = FALSE;
2245 TestCtx ctx = WINPR_C_ARRAY_INIT;
2246 CHECK(ctx_connect(&ctx));
2247 CHECK(send_data(&ctx, FIRST_SEQUENCE, 1, "a"));
2248 CHECK(pump(&ctx));
2249 CHECK(drain(&ctx, 20));
2250 const V3Packet* ack = last_ack(&ctx);
2251 CHECK(ack && (ack->flags & V3_ACK) && (ack->ack == FIRST_SEQUENCE));
2252
2253 /* two keepalive intervals without a datagram: no acknowledgement of the old position */
2254 Sleep(8500);
2255 CHECK(pump(&ctx));
2256 CHECK(drain(&ctx, 20));
2257 CHECK(last_ack(&ctx) == nullptr);
2258
2259 /* a packet without AckOfAcks: still no acknowledgement, and nothing left due, or the
2260 * tunnel thread would poll without waiting */
2261 const V3Out unannounced = { .dummy = TRUE,
2262 .hasData = TRUE,
2263 .dataSeq = FIRST_SEQUENCE + 1,
2264 .payload = (const BYTE*)"x",
2265 .payloadLength = 1 };
2266 CHECK(server_send_v3(&ctx, &unannounced));
2267 CHECK(pump(&ctx));
2268 CHECK(pump(&ctx));
2269 CHECK(rdpudp_get_timeout(ctx.udp) > 0);
2270 CHECK(drain(&ctx, 20));
2271 CHECK(last_ack(&ctx) == nullptr);
2272
2273 const UINT16 ahead = (UINT16)(FIRST_SEQUENCE + 45000);
2274 const V3Out out = { .hasAoA = TRUE,
2275 .aoa = ahead,
2276 .hasData = TRUE,
2277 .dataSeq = ahead,
2278 .channelSeq = 2,
2279 .payload = (const BYTE*)"b",
2280 .payloadLength = 1 };
2281 CHECK(server_send_v3(&ctx, &out));
2282 CHECK(pump(&ctx));
2283 CHECK(delivered_is(&ctx, "ab"));
2284 CHECK(drain(&ctx, 20));
2285 ack = last_ack(&ctx);
2286 CHECK(ack && (ack->flags & V3_ACK) && (ack->ack == ahead));
2287 rc = TRUE;
2288fail:
2289 ctx_free(&ctx);
2290 return rc;
2291}
2292
2293/* Through a 2 s outage Windows went on sending at 20000 packets/s and used 42500 sequence numbers,
2294 * more than half the space: its next packets look old to us. Acknowledging our own position then
2295 * names numbers it has not sent, and Windows ends the connection. Each such packet is
2296 * acknowledged on its own instead, and its chunk is kept. The numbers are those of the capture. */
2297static BOOL packets_past_a_wrap_are_acknowledged_on_their_own(void)
2298{
2299 BOOL rc = FALSE;
2300 TestCtx ctx = WINPR_C_ARRAY_INIT;
2301 CHECK(ctx_connect(&ctx));
2302 CHECK(send_data(&ctx, FIRST_SEQUENCE, 1, "a"));
2303 CHECK(pump(&ctx));
2304 CHECK(drain(&ctx, 20));
2305
2306 /* 23006 below our position as serial arithmetic sees it, 42530 ahead in fact: a run of
2307 * 100 such packets, 70 carrying chunks and 30 dummies */
2308 const UINT16 wrapped = (UINT16)(FIRST_SEQUENCE + 1 + 42530);
2309 const size_t total = 100;
2310 char expected[80] = "a";
2311 for (size_t x = 0; x < total; x++)
2312 {
2313 const UINT16 seq = (UINT16)(wrapped + x);
2314 if (x < 70)
2315 {
2316 const char text[2] = { (char)('A' + (x % 26)), '\0' };
2317 expected[x + 1] = text[0];
2318 CHECK(send_data_aoa(&ctx, seq, (UINT16)(2 + x), text, (UINT16)(wrapped - 6976)));
2319 }
2320 else
2321 {
2322 const V3Out dummy = { .dummy = TRUE,
2323 .hasData = TRUE,
2324 .dataSeq = seq,
2325 .channelSeq = 0,
2326 .payload = (const BYTE*)"x",
2327 .payloadLength = 1 };
2328 CHECK(server_send_v3(&ctx, &dummy));
2329 }
2330 if ((x % 10) == 9)
2331 CHECK(pump(&ctx));
2332 }
2333 CHECK(pump(&ctx));
2334 CHECK(delivered_is(&ctx, expected));
2335
2336 /* the ACK vectors report exactly the run, nothing names our old position */
2337 CHECK(drain(&ctx, 50));
2338 BOOL reported[100] = WINPR_C_ARRAY_INIT;
2339 size_t vectors = 0;
2340 for (size_t x = 0; x < ctx.seenCount; x++)
2341 {
2342 const V3Packet* p = &ctx.seen[x];
2343 CHECK(!(p->flags & V3_ACK) || (p->ack != FIRST_SEQUENCE));
2344 if (!(p->flags & V3_ACKVEC))
2345 continue;
2346 vectors++;
2347 size_t pos = (UINT16)(p->vecBase - wrapped);
2348 for (size_t y = 0; y < p->vecLength; y++)
2349 {
2350 /* run-length entries of received packets only */
2351 CHECK((p->vec[y] & 0xC0) == 0xC0);
2352 for (size_t z = 0; z < (p->vec[y] & 0x3F); z++)
2353 {
2354 CHECK(pos < total);
2355 reported[pos++] = TRUE;
2356 }
2357 }
2358 }
2359 for (size_t x = 0; x < total; x++)
2360 CHECK(reported[x]);
2361 /* batched like any acknowledgement, not one per packet */
2362 CHECK(vectors < total / 4);
2363 rc = TRUE;
2364fail:
2365 ctx_free(&ctx);
2366 return rc;
2367}
2368
2369/* An ACK that rode on our data before a jump of the peer's numbers is not repeated after it,
2370 * where it would name a number the peer did not send. */
2371static BOOL piggybacked_ack_is_not_repeated_after_a_jump(void)
2372{
2373 BOOL rc = FALSE;
2374 TestCtx ctx = WINPR_C_ARRAY_INIT;
2375 CHECK(ctx_connect(&ctx));
2376 /* the peer lets our acknowledgements wait 200 ms, so our data carries the ACK */
2377 const V3Out first = { .hasDelayAck = TRUE,
2378 .maxDelayedAcks = 8,
2379 .delayedAckTimeout = 200,
2380 .hasData = TRUE,
2381 .dataSeq = FIRST_SEQUENCE,
2382 .channelSeq = 1,
2383 .payload = (const BYTE*)"a",
2384 .payloadLength = 1 };
2385 CHECK(server_send_v3(&ctx, &first));
2386 CHECK(pump(&ctx));
2387 CHECK(rdpudp_send(ctx.udp, (const BYTE*)"x", 1));
2388 CHECK(drain(&ctx, 20));
2389 const V3Packet* sent = first_data(&ctx);
2390 CHECK(sent && (sent->flags & V3_ACK) && (sent->ack == FIRST_SEQUENCE));
2391 CHECK(send_ack(&ctx, sent->dataSeq));
2392
2393 /* the peer's numbers jump past half the space */
2394 const UINT16 wrapped = (UINT16)(FIRST_SEQUENCE + 1 + 42530);
2395 for (size_t x = 0; x < 10; x++)
2396 CHECK(send_data_aoa(&ctx, (UINT16)(wrapped + x), (UINT16)(2 + x), "b",
2397 (UINT16)(wrapped - 6976)));
2398 CHECK(pump(&ctx));
2399 Sleep(250);
2400 CHECK(pump(&ctx));
2401 CHECK(drain(&ctx, 20));
2402
2403 BOOL vector = FALSE;
2404 for (size_t x = 0; x < ctx.seenCount; x++)
2405 {
2406 const V3Packet* p = &ctx.seen[x];
2407 CHECK(!(p->flags & V3_ACK) || (p->ack != FIRST_SEQUENCE));
2408 if (p->flags & V3_ACKVEC)
2409 vector = TRUE;
2410 }
2411 CHECK(vector);
2412 rc = TRUE;
2413fail:
2414 ctx_free(&ctx);
2415 return rc;
2416}
2417
2418/* ---------------------------------------------------------------------------------------- */
2419
2420typedef struct
2421{
2422 const char* name;
2423 BOOL (*fn)(void);
2424} TestCase;
2425
2426static const TestCase cases[] = {
2427 { "syn_offers_version_3_with_the_cookie_hash", syn_offers_version_3_with_the_cookie_hash },
2428 { "syn_offers_version_2_without_a_cookie_hash", syn_offers_version_2_without_a_cookie_hash },
2429 { "dummy_packets_are_acknowledged_but_not_delivered",
2430 dummy_packets_are_acknowledged_but_not_delivered },
2431 { "retransmission_is_reordered_back_into_the_stream",
2432 retransmission_is_reordered_back_into_the_stream },
2433 { "ack_of_acks_advances_the_window_without_touching_the_stream",
2434 ack_of_acks_advances_the_window_without_touching_the_stream },
2435 { "ack_of_acks_on_its_own_is_answered", ack_of_acks_on_its_own_is_answered },
2436 { "ack_of_acks_past_its_own_packet_keeps_the_chunk",
2437 ack_of_acks_past_its_own_packet_keeps_the_chunk },
2438 { "ack_of_acks_past_its_own_packet_gets_no_ack_vector",
2439 ack_of_acks_past_its_own_packet_gets_no_ack_vector },
2440 { "ack_of_acks_far_past_its_own_packet_keeps_the_chunk",
2441 ack_of_acks_far_past_its_own_packet_keeps_the_chunk },
2442 { "server_backs_off_once_for_many_timeouts", server_backs_off_once_for_many_timeouts },
2443 { "client_resends_at_least_every_two_seconds", client_resends_at_least_every_two_seconds },
2444 { "server_limits_buffered_chunks_until_verified",
2445 server_limits_buffered_chunks_until_verified },
2446 { "server_ends_a_silent_connection", server_ends_a_silent_connection },
2447 { "server_waits_for_the_fourth_keepalive", server_waits_for_the_fourth_keepalive },
2448 { "server_takes_no_data_while_held", server_takes_no_data_while_held },
2449 { "server_takes_a_lasting_delay_step_as_the_new_base",
2450 server_takes_a_lasting_delay_step_as_the_new_base },
2451 { "server_keeps_cutting_for_its_own_queue", server_keeps_cutting_for_its_own_queue },
2452 { "server_follows_the_base_delay_down", server_follows_the_base_delay_down },
2453 { "server_keepalive_after_a_silence_is_an_ack_of_acks",
2454 server_keepalive_after_a_silence_is_an_ack_of_acks },
2455 { "idle_tunnel_survives_lost_wake_ups", idle_tunnel_survives_lost_wake_ups },
2456 { "idle_tunnel_survives_a_lost_server_keepalive",
2457 idle_tunnel_survives_a_lost_server_keepalive },
2458 { "idle_tunnel_survives_a_lost_client_keepalive",
2459 idle_tunnel_survives_a_lost_client_keepalive },
2460 { "server_keeps_its_window_when_acks_were_lost_in_a_silence",
2461 server_keeps_its_window_when_acks_were_lost_in_a_silence },
2462 { "server_refuses_a_short_syn", server_refuses_a_short_syn },
2463 { "server_follows_large_ack_of_acks_jumps", server_follows_large_ack_of_acks_jumps },
2464 { "server_does_not_find_a_skipped_slot_a_wrap_later",
2465 server_does_not_find_a_skipped_slot_a_wrap_later },
2466 { "server_repeats_ack_of_acks_until_the_first_ack",
2467 server_repeats_ack_of_acks_until_the_first_ack },
2468 { "server_ignores_an_ack_past_what_it_sent", server_ignores_an_ack_past_what_it_sent },
2469 { "server_samples_the_rtt_from_the_handshake", server_samples_the_rtt_from_the_handshake },
2470 { "server_drops_an_oversized_chunk", server_drops_an_oversized_chunk },
2471 { "server_takes_its_base_from_an_ackofacks", server_takes_its_base_from_an_ackofacks },
2472 { "server_keeps_what_lies_below_a_behind_report",
2473 server_keeps_what_lies_below_a_behind_report },
2474 { "server_does_not_report_a_packet_behind_its_window",
2475 server_does_not_report_a_packet_behind_its_window },
2476 { "late_packet_behind_the_window_fills_the_hole",
2477 late_packet_behind_the_window_fills_the_hole },
2478 { "retransmitted_packets_are_acknowledged_again",
2479 retransmitted_packets_are_acknowledged_again },
2480 { "ack_vector_is_not_lost_to_outgoing_data", ack_vector_is_not_lost_to_outgoing_data },
2481 { "retransmitted_channel_data_is_not_delivered_twice",
2482 retransmitted_channel_data_is_not_delivered_twice },
2483 { "gap_produces_an_ack_vector_rather_than_a_cumulative_ack",
2484 gap_produces_an_ack_vector_rather_than_a_cumulative_ack },
2485 { "ack_advertises_the_largest_window", ack_advertises_the_largest_window },
2486 { "channel_sequence_wraps_past_zero", channel_sequence_wraps_past_zero },
2487 { "real_server_ack_with_delayed_acks_and_data", real_server_ack_with_delayed_acks_and_data },
2488 { "ack_of_acks_reports_the_oldest_unacknowledged_packet",
2489 ack_of_acks_reports_the_oldest_unacknowledged_packet },
2490 { "acknowledgements_survive_sequence_wraparound",
2491 acknowledgements_survive_sequence_wraparound },
2492 { "ack_of_acks_resyncs_after_a_silence", ack_of_acks_resyncs_after_a_silence },
2493 { "packets_past_a_wrap_are_acknowledged_on_their_own",
2494 packets_past_a_wrap_are_acknowledged_on_their_own },
2495 { "piggybacked_ack_is_not_repeated_after_a_jump",
2496 piggybacked_ack_is_not_repeated_after_a_jump },
2497};
2498
2499int TestRdpUdp(int argc, char* argv[])
2500{
2501 WINPR_UNUSED(argc);
2502 WINPR_UNUSED(argv);
2503
2504 WSADATA wsaData = WINPR_C_ARRAY_INIT;
2505 if (WSAStartup(MAKEWORD(2, 2), &wsaData) != 0)
2506 return -1;
2507
2508 int rc = 0;
2509 for (size_t x = 0; x < ARRAYSIZE(cases); x++)
2510 {
2511 const BOOL ok = cases[x].fn();
2512 (void)printf("%s %s\n", ok ? "ok " : "FAILED", cases[x].name);
2513 if (!ok)
2514 rc = -1;
2515 }
2516
2517 WSACleanup();
2518 return rc;
2519}
Layout layout(float leftWidth, float leftHeight, float rightWidth, float rightHeight, float width, float margin)