FreeRDP
Loading...
Searching...
No Matches
server_tunnel.c
1
17
18#include <string.h>
19
20#include <winpr/assert.h>
21#include <winpr/cast.h>
22#include <winpr/collections.h>
23#include <winpr/crt.h>
24#include <winpr/stream.h>
25
26#include <freerdp/log.h>
27#include <freerdp/multitransport.h>
28#include <freerdp/channels/drdynvc.h>
29#include <freerdp/utils/drdynvc.h>
30
31#include "rdp.h"
32#include "server.h"
33#include "server_tunnel.h"
34
35#define TAG FREERDP_TAG("core.server")
36
37/* Client tunnel PDUs held until the Soft-Sync Response. From this many on the tunnel accepts
38 * no more data from the client (multitransport_hold_tunnel_data), which sends it again once the
39 * Response is in: a client may write on the tunnel as soon as it has sent the Response on TCP,
40 * and TCP can be the slower of the two. */
41#define SOFT_SYNC_HOLD_BACKLOG 1024
42#define SOFT_SYNC_HOLD_BACKLOG_BYTES (1024ull * 1024ull)
43/* What was already on its way to the main loop when the hold began still arrives, at most what
44 * the main loop's event queue takes. More than that means the hold does not work, and the
45 * connection ends. A client that never responds can pin this memory for the session. */
46#define SOFT_SYNC_MAX_BACKLOG ((size_t)256 * 1024)
47#define SOFT_SYNC_MAX_BACKLOG_BYTES (48ull * 1024ull * 1024ull)
48
49/* Timeout for channel Create Response. After this, open channels are moved and unanswered
50 * ones remain on TCP. */
51#define SOFT_SYNC_MAX_WAIT_MS 10000
52
53/* vcm->queue message IDs specifying the transport for drdynvc PDUs */
54typedef enum WINPR_C23_ENUM_TYPE(uint32_t)
55{
56 WTS_QUEUE_TCP = 0,
57 WTS_QUEUE_TUNNEL = 1,
58 WTS_QUEUE_WAKE = 2 /* No PDU: wakes the drain to initiate Soft-Sync */
59} WTS_QUEUE_ID;
60
61/* Post a message instead of just signaling the event. The drain only resets the event after
62 * processing the last message, so signaling an empty queue would leave the event set. */
63static void wts_tunnel_wake_drain(WTSVirtualChannelManager* vcm)
64{
65 WINPR_ASSERT(vcm);
66 if (!MessageQueue_Post(vcm->queue, nullptr, WTS_QUEUE_WAKE, nullptr, nullptr))
67 WLog_WARN(TAG, "unable to wake the channel manager for Soft-Sync");
68}
69
70/* Soft-Sync as described in [MS-RDPEDYC] 3.1.5.3 */
71typedef enum WINPR_C23_ENUM_TYPE(uint8_t)
72{
73 SOFT_SYNC_STATE_NONE = 0, /* All dynamic channels are on TCP */
74 SOFT_SYNC_STATE_SENT =
75 1, /* Request sent; channels moved to the tunnel are transmitted via UDP */
76 SOFT_SYNC_STATE_ANSWERED = 2, /* Client responded; tunnel data has been processed */
77} WTS_SOFT_SYNC_STATE;
78
79/* Associated with the connection thread. Since Soft-Sync may run on the channel manager drain
80 * thread, softSyncState, softSyncWaitStart, clientOnTunnel, and the backlog are protected by
81 * the vcm->dynamicVirtualChannels lock. */
82struct s_wts_tunnel
83{
84 wtsTunnelReadPduFn readPdu;
85 LONG tunnelReady; /* Accessed by other threads; use Interlocked functions */
86 LONG softSyncDue; /* Trigger for Soft-Sync; Interlocked only */
87 UINT64 softSyncWaitStart; /* GetTickCount64() timestamp when Soft-Sync first waited for a
88 channel, or 0. */
89 WTS_SOFT_SYNC_STATE softSyncState;
90 BOOL clientOnTunnel; /* True if the client's Soft-Sync Response lists this tunnel. */
91 wQueue*
92 tunnelBacklog; /* Tunnel PDUs received from the client prior to the Soft-Sync Response. */
93 size_t backlogBytes; /* Total number of bytes in tunnelBacklog. */
94 BOOL written; /* Indicates that tunnel PDUs have been queued and require flushing. */
95};
96
97WINPR_ATTR_NODISCARD
98static BOOL wts_queue_item(rdpPeerChannel* channel, BYTE* buffer, UINT32 length, BOOL tunnel)
99{
100 WINPR_ASSERT(channel);
101 WINPR_ASSERT(channel->vcm);
102 WINPR_ASSERT(channel->channelId <= UINT16_MAX);
103
104 const UINT16 channelId = (UINT16)channel->channelId;
105 const WTS_QUEUE_ID id = tunnel ? WTS_QUEUE_TUNNEL : WTS_QUEUE_TCP;
106 return MessageQueue_Post(channel->vcm->queue, (void*)(UINT_PTR)channelId, id, (void*)buffer,
107 (void*)(UINT_PTR)length);
108}
109
110/* Queues a copy of a drdynvc PDU for TCP or the tunnel. */
111WINPR_ATTR_NODISCARD
112static BOOL wts_queue_drdynvc_pdu(WTSVirtualChannelManager* vcm, const BYTE* data, size_t length,
113 BOOL tunnel)
114{
115 WINPR_ASSERT(vcm);
116 WINPR_ASSERT(vcm->drdynvc_channel);
117 WINPR_ASSERT(data || (length == 0));
118 if ((length == 0) || (length > UINT32_MAX))
119 return FALSE;
120 BYTE* buffer = malloc(length);
121 if (!buffer)
122 return FALSE;
123 memcpy(buffer, data, length);
124 if (!wts_queue_item(vcm->drdynvc_channel, buffer, WINPR_ASSERTING_INT_CAST(UINT32, length),
125 tunnel))
126 {
127 free(buffer);
128 return FALSE;
129 }
130 // NOLINTNEXTLINE(clang-analyzer-unix.Malloc): the queue takes ownership of buffer
131 return TRUE;
132}
133
134/* Processes a client PDU received on the tunnel. Capabilities and Soft-Sync PDUs are only
135 * valid on the drdynvc static channel. */
136WINPR_ATTR_NODISCARD
137static BOOL wts_read_tunnel_pdu(WTSVirtualChannelManager* vcm, const BYTE* data, size_t length)
138{
139 WINPR_ASSERT(vcm);
140 WINPR_ASSERT(data || (length == 0));
141 if (!vcm->drdynvc_channel || (vcm->drdynvc_state != DRDYNVC_STATE_READY) || (length < 1))
142 return FALSE;
143
144 wStream buffer = WINPR_C_ARRAY_INIT;
145 wStream* s = Stream_StaticConstInit(&buffer, data, length);
146 if (!s)
147 return FALSE;
148 const UINT8 value = Stream_Get_UINT8(s);
149 const UINT8 Cmd = (UINT8)((value & 0xf0u) >> 4u);
150 const UINT8 Sp = (UINT8)((value & 0x0cu) >> 2u);
151 const UINT8 cbChId = (UINT8)(value & 0x03u);
152 switch (Cmd)
153 {
154 case CAPABILITY_REQUEST_PDU:
155 case SOFT_SYNC_REQUEST_PDU:
156 case SOFT_SYNC_RESPONSE_PDU:
157 WLog_WARN(TAG, "encountered %s on the tunnel, terminating the connection",
158 drdynvc_get_packet_type(Cmd));
159 return FALSE;
160 default:
161 return vcm->tunnel->readPdu(vcm->drdynvc_channel, s, Cmd, Sp, cbChId, TRUE);
162 }
163}
164
165/* The connection's multitransport, nullptr without one (unit tests). */
166WINPR_ATTR_NODISCARD
167static rdpMultitransport* wts_tunnel_multitransport(const WTSVirtualChannelManager* vcm)
168{
169 WINPR_ASSERT(vcm);
170 if (!vcm->client || !vcm->client->context || !vcm->client->context->rdp)
171 return nullptr;
172 return vcm->client->context->rdp->multitransport;
173}
174
175/* [MS-RDPEDYC] 2.2.5.2 DYNVC_SOFT_SYNC_RESPONSE: Specifies the tunnels the client writes on;
176 * the server will also read from these tunnels henceforth (3.3.5.3.2). */
177BOOL wts_tunnel_read_soft_sync_response(WTSVirtualChannelManager* vcm, wStream* s)
178{
179 WINPR_ASSERT(vcm);
180 WINPR_ASSERT(s);
181
182 /* No request outstanding, as always without a tunnel: logged and ignored whatever it
183 * holds, as before there was Soft-Sync. Only this thread takes the state out of SENT. */
184 HashTable_Lock(vcm->dynamicVirtualChannels);
185 const BOOL expected = (vcm->tunnel->softSyncState == SOFT_SYNC_STATE_SENT);
186 HashTable_Unlock(vcm->dynamicVirtualChannels);
187 if (!expected)
188 {
189 WLog_WARN(TAG, "received an unexpected Soft-Sync response");
190 return TRUE;
191 }
192
193 if (!Stream_CheckAndLogRequiredLength(TAG, s, 5))
194 return FALSE;
195 Stream_Seek_UINT8(s); /* Skip padding byte */
196 const UINT32 count = Stream_Get_UINT32(s);
197 if (!Stream_CheckAndLogRequiredLengthOfSize(TAG, s, count, sizeof(UINT32)))
198 return FALSE;
199 BOOL reliable = FALSE;
200 for (UINT32 x = 0; x < count; x++)
201 {
202 if (Stream_Get_UINT32(s) == TUNNELTYPE_UDPFECR)
203 reliable = TRUE;
204 }
205
206 BOOL rc = TRUE;
207 HashTable_Lock(vcm->dynamicVirtualChannels);
208 /* No request outstanding: assume no tunnel, log and continue */
209 if (vcm->tunnel->softSyncState != SOFT_SYNC_STATE_SENT)
210 {
211 WLog_WARN(TAG, "received an unexpected Soft-Sync response");
212 goto out;
213 }
214
215 vcm->tunnel->softSyncState = SOFT_SYNC_STATE_ANSWERED;
216 vcm->tunnel->clientOnTunnel = reliable;
217 WLog_INFO(TAG, "Soft-Sync Response: the client %s the reliable UDP tunnel",
218 reliable ? "writes on" : "does not use");
219
220 /* [MS-RDPEDYC] 3.2.5.3.2: The response lists all tunnels the client writes on. The server
221 * continues writing to the tunnel specified in its request, but only reads those
222 * listed by the client. */
223 if (!reliable && (Queue_Count(vcm->tunnel->tunnelBacklog) > 0))
224 {
225 WLog_ERR(TAG, "client wrote to a tunnel not named in its Soft-Sync Response");
226 rc = FALSE;
227 goto out;
228 }
229
230 wStream* held = nullptr;
231 vcm->tunnel->backlogBytes = 0;
232 while (rc && (held = Queue_Dequeue(vcm->tunnel->tunnelBacklog)))
233 {
234 rc = wts_read_tunnel_pdu(vcm, Stream_Buffer(held), Stream_Length(held));
235 Stream_Release(held);
236 }
237out:
238 HashTable_Unlock(vcm->dynamicVirtualChannels);
239 /* the backlog is processed, the client's data is taken as it comes from here on */
240 multitransport_hold_tunnel_data(wts_tunnel_multitransport(vcm), FALSE);
241 return rc;
242}
243
244/* Moves all open dynamic channels to the tunnel via a Soft-Sync Request ([MS-RDPEDYC]
245 * 3.3.5.3.1). The request is sent over TCP after any previously queued channel data; subsequent
246 * data is sent via the tunnel. Each channel's writeLock is held across both steps to prevent
247 * messages from crossing the switch. */
248WINPR_ATTR_NODISCARD
249static BOOL wts_soft_sync(WTSVirtualChannelManager* vcm)
250{
251 WINPR_ASSERT(vcm);
252
253 if (!InterlockedCompareExchange(&vcm->tunnel->tunnelReady, 0, 0) || !vcm->drdynvc_channel ||
254 (vcm->drdynvc_state != DRDYNVC_STATE_READY))
255 return TRUE;
256 /* tunnelReady is cleared when the main loop handles the tunnel's failure. A request sent
257 * between the failure and that would count as channels moved, and end a connection that
258 * could have stayed on TCP. */
259 if (multitransport_tunnel_has_failed(wts_tunnel_multitransport(vcm)))
260 return TRUE;
261
262 BOOL rc = FALSE;
263 ULONG_PTR* keys = nullptr;
264 rdpPeerChannel** channels = nullptr;
265 rdpPeerChannel** moving = nullptr;
266 size_t count = 0;
267 wStream* s = nullptr;
268
269 /* Both the peer thread and the channel manager drain thread may call this; only one
270 * should send the request. */
271 HashTable_Lock(vcm->dynamicVirtualChannels);
272 /* Re-verify tunnelReady under the lock: wts_tunnel_state_changed may clear it before
273 * acquiring the lock to decide if a lost tunnel terminates the connection or stays on TCP. */
274 if ((vcm->tunnel->softSyncState != SOFT_SYNC_STATE_NONE) ||
275 !InterlockedCompareExchange(&vcm->tunnel->tunnelReady, 0, 0))
276 {
277 rc = TRUE;
278 goto out;
279 }
280 const UINT64 waitStart = vcm->tunnel->softSyncWaitStart;
281 const BOOL waitedLong =
282 (waitStart != 0) && (GetTickCount64() - waitStart > SOFT_SYNC_MAX_WAIT_MS);
283 const size_t total = HashTable_GetKeys(vcm->dynamicVirtualChannels, &keys);
284 if (total > 0)
285 {
286 channels = (rdpPeerChannel**)calloc(total, sizeof(rdpPeerChannel*));
287 if (!channels)
288 goto out;
289 }
290 for (size_t x = 0; x < total; x++)
291 {
292 rdpPeerChannel* channel =
293 HashTable_GetItemValue(vcm->dynamicVirtualChannels, (void*)keys[x]);
294 /* Moving other channels now would permanently leave unanswered channels on TCP. Retry
295 * upon client response or after SOFT_SYNC_MAX_WAIT_MS. */
296 if (channel && (channel->dvc_open_state == DVC_OPEN_STATE_NONE))
297 {
298 if (!waitedLong)
299 {
300 if (waitStart == 0)
301 vcm->tunnel->softSyncWaitStart = GetTickCount64();
302 rc = TRUE;
303 goto out;
304 }
305 WLog_WARN(TAG, "missing Create Response for channel %" PRIu32 ", it stays on TCP",
306 channel->channelId);
307 }
308 if (channel && (channel->dvc_open_state == DVC_OPEN_STATE_SUCCEEDED))
309 channels[count++] = channel;
310 }
311 if (count == 0)
312 {
313 /* Nothing to move; the next channel open will retry. Once the timeout expires, prevent
314 * unanswered channels from triggering a full rescan on every drain. */
315 if (waitedLong)
316 vcm->tunnel->softSyncWaitStart = 0;
317 rc = TRUE;
318 goto out;
319 }
320 /* NumberOfDVCs is a 16-bit field */
321 if (count > UINT16_MAX)
322 {
323 WLog_ERR(TAG, "%" PRIuz " dynamic channels are too many for a Soft-Sync Request", count);
324 goto out;
325 }
326
327 /* The list is processed while holding writeLocks; any channel closed in the meantime has
328 * already posted its Close Request on TCP and is excluded (see wts_tunnel_close_request). */
329 for (size_t x = 0; x < count; x++)
330 EnterCriticalSection(&channels[x]->writeLock);
331 moving = (rdpPeerChannel**)calloc(count, sizeof(rdpPeerChannel*));
332 size_t moves = 0;
333 if (moving)
334 {
335 for (size_t x = 0; x < count; x++)
336 {
337 if (!channels[x]->closing)
338 moving[moves++] = channels[x];
339 }
340 }
341 if (!moving || (moves == 0))
342 {
343 rc = (moving != nullptr);
344 goto unlock;
345 }
346
347 /* DYNVC_SOFT_SYNC_REQUEST: The length is calculated starting from the Length field. */
348 const size_t listLength = 4 + 2 + sizeof(UINT32) * moves;
349 s = Stream_New(nullptr, 2 + 4 + 2 + 2 + listLength);
350 if (!s)
351 goto unlock;
352 /* Stream_Write macros may evaluate their arguments multiple times. */
353 const UINT8 header = (UINT8)((UINT32)SOFT_SYNC_REQUEST_PDU << 4u);
354 const UINT16 flags =
355 (UINT16)((UINT32)SOFT_SYNC_TCP_FLUSHED | (UINT32)SOFT_SYNC_CHANNEL_LIST_PRESENT);
356 const UINT32 length = WINPR_ASSERTING_INT_CAST(UINT32, 4 + 2 + 2 + listLength);
357 const UINT16 dvcs = WINPR_ASSERTING_INT_CAST(UINT16, moves);
358 Stream_Write_UINT8(s, header);
359 Stream_Write_UINT8(s, 0); /* Padding byte */
360 Stream_Write_UINT32(s, length); /* The length of the PDU */
361 Stream_Write_UINT16(s, flags); /* Soft-Sync Request flags */
362 Stream_Write_UINT16(s, 1); /* Number of tunnels */
363 Stream_Write_UINT32(s, TUNNELTYPE_UDPFECR); /* Specify the tunnel type */
364 Stream_Write_UINT16(s, dvcs); /* Number of Dynamic Virtual Channels */
365 for (size_t x = 0; x < moves; x++)
366 Stream_Write_UINT32(s, moving[x]->channelId);
367
368 rc = wts_queue_drdynvc_pdu(vcm, Stream_Buffer(s), Stream_GetPosition(s), FALSE);
369 if (rc)
370 {
371 for (size_t x = 0; x < moves; x++)
372 moving[x]->tunnel = TRUE;
373 vcm->tunnel->softSyncState = SOFT_SYNC_STATE_SENT;
374 vcm->tunnel->softSyncWaitStart = 0;
375 WLog_INFO(TAG,
376 "Soft-Sync Request: %" PRIuz " dynamic channel(s) are moving to the UDP tunnel",
377 moves);
378 for (size_t x = 0; x < moves; x++)
379 WLog_DBG(TAG, " %" PRIu32 " %s", moving[x]->channelId, moving[x]->channelName);
380 }
381
382unlock:
383 for (size_t x = 0; x < count; x++)
384 LeaveCriticalSection(&channels[x]->writeLock);
385
386out:
387 HashTable_Unlock(vcm->dynamicVirtualChannels);
388 Stream_Free(s, TRUE);
389 free((void*)moving);
390 free((void*)channels);
391 free(keys);
392 return rc;
393}
394
395WINPR_ATTR_NODISCARD
396static BOOL wts_tunnel_data_received(void* custom, UINT32 tunnelType, wStream* s)
397{
398 WTSVirtualChannelManager* vcm = custom;
399 WINPR_ASSERT(vcm);
400 WINPR_ASSERT(s);
401 WINPR_UNUSED(tunnelType);
402
403 BOOL rc = FALSE;
404 BOOL hold = FALSE;
405 HashTable_Lock(vcm->dynamicVirtualChannels);
406 /* [MS-RDPEDYC] 3.3.5.3.2: The server does not process tunnel data before the Soft-Sync Response
407 */
408 if (vcm->tunnel->softSyncState == SOFT_SYNC_STATE_NONE)
409 {
410 /* No channels should be on the tunnel before a Soft-Sync Request. */
411 WLog_ERR(TAG, "client wrote to the tunnel before a Soft-Sync Request");
412 }
413 else if (vcm->tunnel->softSyncState != SOFT_SYNC_STATE_ANSWERED)
414 {
415 const size_t length = Stream_Length(s);
416 const size_t held =
417 WINPR_ASSERTING_INT_CAST(size_t, Queue_Count(vcm->tunnel->tunnelBacklog));
418 hold = (held + 1 >= SOFT_SYNC_HOLD_BACKLOG) ||
419 (length >= SOFT_SYNC_HOLD_BACKLOG_BYTES - vcm->tunnel->backlogBytes) ||
420 (vcm->tunnel->backlogBytes >= SOFT_SYNC_HOLD_BACKLOG_BYTES);
421 if ((held >= SOFT_SYNC_MAX_BACKLOG) ||
422 (length > SOFT_SYNC_MAX_BACKLOG_BYTES - vcm->tunnel->backlogBytes))
423 WLog_ERR(TAG, "tunnel data continues to arrive without a Soft-Sync Response");
424 else if (Queue_Enqueue(vcm->tunnel->tunnelBacklog, s))
425 {
426 /* Backlog now owns s. */
427 vcm->tunnel->backlogBytes += length;
428 s = nullptr;
429 rc = TRUE;
430 }
431 }
432 else if (!vcm->tunnel->clientOnTunnel)
433 WLog_ERR(TAG, "the client wrote data on a tunnel that its Soft-Sync Response did not list");
434 else
435 rc = wts_read_tunnel_pdu(vcm, Stream_Buffer(s), Stream_Length(s));
436 HashTable_Unlock(vcm->dynamicVirtualChannels);
437 if (hold)
438 multitransport_hold_tunnel_data(wts_tunnel_multitransport(vcm), TRUE);
439 if (s)
440 Stream_Release(s);
441 return rc;
442}
443
444WINPR_ATTR_NODISCARD
445static BOOL wts_tunnel_state_changed(void* custom, UINT32 tunnelType,
446 FreeRDP_MultitransportTunnelState state)
447{
448 WTSVirtualChannelManager* vcm = custom;
449 WINPR_ASSERT(vcm);
450 if (tunnelType != TUNNELTYPE_UDPFECR)
451 return TRUE;
452 const BOOL ready = (state == FREERDP_MULTITRANSPORT_TUNNEL_READY);
453 /* Use compare-exchange as WinPR's InterlockedExchange reads the old value non-atomically.
454 * Only this thread writes the value. */
455 const LONG old = InterlockedCompareExchange(&vcm->tunnel->tunnelReady, 0, 0);
456 if (InterlockedCompareExchange(&vcm->tunnel->tunnelReady, ready ? 1 : 0, old) != old)
457 WLog_DBG(TAG, "tunnel state was updated by another thread");
458 /* Soft-Sync only moves channels from TCP to UDP ([MS-RDPEDYC] 3.1.5.3). Once moved,
459 tunnel loss results in data loss and session termination; otherwise, the session remains
460 on TCP. */
461 HashTable_Lock(vcm->dynamicVirtualChannels);
462 const BOOL moved = (vcm->tunnel->softSyncState != SOFT_SYNC_STATE_NONE);
463 HashTable_Unlock(vcm->dynamicVirtualChannels);
464 if (!ready && moved)
465 {
466 WLog_WARN(TAG, "UDP tunnel carrying channels failed, terminating the connection");
467 return FALSE;
468 }
469 return wts_soft_sync(vcm);
470}
471
472BOOL wts_tunnel_new(WTSVirtualChannelManager* vcm, rdpContext* context, wtsTunnelReadPduFn readPdu)
473{
474 WINPR_ASSERT(vcm);
475 WINPR_ASSERT(vcm->dynamicVirtualChannels);
476 WINPR_ASSERT(readPdu);
477
478 vcm->tunnel = calloc(1, sizeof(struct s_wts_tunnel));
479 if (!vcm->tunnel)
480 return FALSE;
481 vcm->tunnel->readPdu = readPdu;
482 vcm->tunnel->tunnelBacklog = Queue_New(FALSE, -1, -1);
483 if (!vcm->tunnel->tunnelBacklog)
484 return FALSE;
485
486 const FreeRDP_MultitransportDvcCallbacks callbacks = {
487 .TunnelDataReceived = wts_tunnel_data_received,
488 .TunnelStateChanged = wts_tunnel_state_changed,
489 };
490 if (!freerdp_multitransport_set_dvc_callbacks(context, &callbacks, vcm))
491 return FALSE;
492 /* TunnelStateChanged is called when the state changes. A channel manager opened after
493 * the tunnel became ready would wait for a call that has already been made. */
494 if ((freerdp_multitransport_get_tunnel_state(context, TUNNELTYPE_UDPFECR) ==
495 FREERDP_MULTITRANSPORT_TUNNEL_READY) &&
496 (InterlockedCompareExchange(&vcm->tunnel->tunnelReady, 1, 0) == 0))
497 WLog_DBG(TAG, "the UDP tunnel was ready before the channel manager opened");
498 return TRUE;
499}
500
501void wts_tunnel_free(WTSVirtualChannelManager* vcm)
502{
503 WINPR_ASSERT(vcm);
504
505 if (vcm->client && vcm->client->context &&
506 !freerdp_multitransport_set_dvc_callbacks(vcm->client->context, nullptr, nullptr))
507 WLog_WARN(TAG, "failed to remove the multitransport callbacks");
508 multitransport_hold_tunnel_data(wts_tunnel_multitransport(vcm), FALSE);
509 if (!vcm->tunnel)
510 return;
511 if (vcm->tunnel->tunnelBacklog)
512 {
513 wStream* held = nullptr;
514 while ((held = Queue_Dequeue(vcm->tunnel->tunnelBacklog)))
515 Stream_Release(held);
516 Queue_Free(vcm->tunnel->tunnelBacklog);
517 }
518 free(vcm->tunnel);
519 vcm->tunnel = nullptr;
520}
521
522void wts_tunnel_channel_opened(WTSVirtualChannelManager* vcm)
523{
524 WINPR_ASSERT(vcm);
525 WINPR_ASSERT(vcm->tunnel);
526 /* May be called from an application thread via WTSVirtualChannelClose. Waking the drain
527 * triggers Soft-Sync (wts_tunnel_start_soft_sync_if_due). Only the first call in a burst
528 * posts a message; others are either already queued or re-armed by wts_tunnel_after_drain. */
529 if (InterlockedIncrement(&vcm->tunnel->softSyncDue) == 1)
530 wts_tunnel_wake_drain(vcm);
531}
532
533BOOL wts_tunnel_is_soft_sync_response(UINT8 Cmd)
534{
535 return Cmd == SOFT_SYNC_RESPONSE_PDU;
536}
537
538BOOL wts_tunnel_start_soft_sync_if_due(WTSVirtualChannelManager* vcm)
539{
540 WINPR_ASSERT(vcm);
541 WINPR_ASSERT(vcm->tunnel);
542
543 HashTable_Lock(vcm->dynamicVirtualChannels);
544 const UINT64 waitStart = vcm->tunnel->softSyncWaitStart;
545 HashTable_Unlock(vcm->dynamicVirtualChannels);
546 const BOOL waitedLong =
547 (waitStart != 0) && (GetTickCount64() - waitStart > SOFT_SYNC_MAX_WAIT_MS);
548 /* Consume the flag; use compare-exchange as WinPR's InterlockedExchange is not atomic. */
549 LONG due = InterlockedCompareExchange(&vcm->tunnel->softSyncDue, 0, 0);
550 while (due != 0)
551 {
552 const LONG seen = InterlockedCompareExchange(&vcm->tunnel->softSyncDue, 0, due);
553 if (seen == due)
554 break;
555 due = seen;
556 }
557 if ((due == 0) && !waitedLong)
558 return TRUE;
559 return wts_soft_sync(vcm);
560}
561
562BOOL wts_tunnel_send_message(WTSVirtualChannelManager* vcm, UINT32 id, const BYTE* buffer,
563 UINT32 length, BOOL* status)
564{
565 WINPR_ASSERT(vcm);
566 WINPR_ASSERT(vcm->tunnel);
567 WINPR_ASSERT(status);
568
569 if (id == WTS_QUEUE_WAKE)
570 return TRUE;
571 if (id != WTS_QUEUE_TUNNEL)
572 return FALSE;
573
574 WINPR_ASSERT(vcm->client);
575 WINPR_ASSERT(vcm->client->context);
576 if (multitransport_queue_dvc(vcm->client->context->rdp->multitransport, buffer, length))
577 vcm->tunnel->written = TRUE;
578 else
579 {
580 WLog_ERR(TAG, "unable to write a dynamic channel PDU to the UDP tunnel");
581 *status = FALSE;
582 }
583 return TRUE;
584}
585
586BOOL wts_tunnel_after_drain(WTSVirtualChannelManager* vcm, BOOL status)
587{
588 WINPR_ASSERT(vcm);
589 WINPR_ASSERT(vcm->tunnel);
590
591 /* If a channel responded during this drain, its wake message might have been processed
592 * before Soft-Sync saw the flag; trigger the drain again. */
593 if (InterlockedCompareExchange(&vcm->tunnel->softSyncDue, 0, 0) != 0)
594 wts_tunnel_wake_drain(vcm);
595
596 /* the next drain starts clean */
597 const BOOL written = vcm->tunnel->written;
598 vcm->tunnel->written = FALSE;
599 if (!status || !written)
600 return status;
601
602 WINPR_ASSERT(vcm->client->context->rdp);
603 if (!multitransport_flush_dvc(vcm->client->context->rdp->multitransport))
604 {
605 WLog_ERR(TAG, "unable to write dynamic channel PDUs over the UDP tunnel");
606 return FALSE;
607 }
608 return TRUE;
609}
610
611BOOL wts_tunnel_open_channel(WTSVirtualChannelManager* vcm, rdpPeerChannel* channel, wStream* s,
612 BOOL* onTunnel)
613{
614 WINPR_ASSERT(vcm);
615 WINPR_ASSERT(vcm->tunnel);
616 WINPR_ASSERT(channel);
617 WINPR_ASSERT(s);
618 WINPR_ASSERT(onTunnel);
619
620 /* Client responds on the same transport. */
621 BOOL rc = TRUE;
622 HashTable_Lock(vcm->dynamicVirtualChannels);
623 channel->tunnel = (vcm->tunnel->softSyncState != SOFT_SYNC_STATE_NONE) &&
624 InterlockedCompareExchange(&vcm->tunnel->tunnelReady, 0, 0);
625 *onTunnel = channel->tunnel;
626 if (channel->tunnel)
627 rc = wts_queue_drdynvc_pdu(vcm, Stream_Buffer(s), Stream_GetPosition(s), TRUE);
628 HashTable_Unlock(vcm->dynamicVirtualChannels);
629 return rc;
630}
631
632BOOL wts_tunnel_close_request(rdpPeerChannel* channel, const BYTE* data, size_t length,
633 BOOL* status)
634{
635 WINPR_ASSERT(channel);
636 WINPR_ASSERT(status);
637
638 /* Send the Close Request now. A Soft-Sync waiting for this writeLock must not list the
639 * channel ([MS-RDPEDYC] 2.2.5.1 lists the channels the server will send data for). */
640 channel->closing = TRUE;
641 if (!channel->tunnel)
642 return FALSE;
643 *status = wts_queue_drdynvc_pdu(channel->vcm, data, length, TRUE);
644 return TRUE;
645}
646
647BOOL wts_tunnel_queue_send_item(rdpPeerChannel* channel, BYTE* buffer, UINT32 length, BOOL* status)
648{
649 WINPR_ASSERT(channel);
650 WINPR_ASSERT(channel->vcm);
651 WINPR_ASSERT(status);
652
653 if (!channel->tunnel)
654 return FALSE;
655 *status = wts_queue_item(channel->vcm->drdynvc_channel, buffer, length, TRUE);
656 return TRUE;
657}
Dynamic virtual channel hooks of the client side tunnels.