FreeRDP
Loading...
Searching...
No Matches
udplistener.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/crypto.h>
25#include <winpr/interlocked.h>
26#include <winpr/synch.h>
27#include <winpr/thread.h>
28#include <winpr/winsock.h>
29
30#if !defined(_WIN32)
31#include <netdb.h>
32#endif
33
34#include <freerdp/log.h>
35
36#include "rdpudp.h"
37#include "udplistener_internal.h"
38
39#define TAG FREERDP_TAG("core.udplistener")
40
41static freerdp_udp_listener* g_listener;
42static CRITICAL_SECTION g_listenerLock;
43static INIT_ONCE g_listenerOnce = INIT_ONCE_STATIC_INIT;
44
45/* Random seed for table hashes to prevent hash collision attacks. */
46static UINT32 g_hashSeed;
47
48WINPR_ATTR_NODISCARD
49static BOOL CALLBACK udplistener_init(WINPR_ATTR_UNUSED PINIT_ONCE once,
50 WINPR_ATTR_UNUSED PVOID param,
51 WINPR_ATTR_UNUSED PVOID* context)
52{
53 if (winpr_RAND(&g_hashSeed, sizeof(g_hashSeed)) < 0)
54 return FALSE;
55 return InitializeCriticalSectionAndSpinCount(&g_listenerLock, 4000);
56}
57
58/* MurmurHash3 fmix32, the final mixing step for table hashes. FNV-1a alone may map keys with
59 * identical low bits to the same bucket regardless of the seed; this mixes all bits into the
60 * low bits. */
61WINPR_ATTR_NODISCARD
62static UINT32 udplistener_fmix32(UINT32 hash)
63{
64 hash ^= hash >> 16;
65 hash *= 0x85ebca6bu;
66 hash ^= hash >> 13;
67 hash *= 0xc2b2ae35u;
68 hash ^= hash >> 16;
69 return hash;
70}
71
72/* The entriesByAddress table is keyed by struct sockaddr_storage. */
73WINPR_ATTR_NODISCARD
74static UINT32 udplistener_address_hash(const void* key)
75{
76 const struct sockaddr_storage* addr = key;
77 WINPR_ASSERT(addr);
78
79 const BYTE* bytes = nullptr;
80 size_t length = 0;
81 UINT16 port = 0;
82 if (addr->ss_family == AF_INET)
83 {
84 const struct sockaddr_in* in = (const struct sockaddr_in*)addr;
85 bytes = (const BYTE*)&in->sin_addr;
86 length = sizeof(in->sin_addr);
87 port = in->sin_port;
88 }
89 else if (addr->ss_family == AF_INET6)
90 {
91 const struct sockaddr_in6* in6 = (const struct sockaddr_in6*)addr;
92 bytes = (const BYTE*)&in6->sin6_addr;
93 length = sizeof(in6->sin6_addr);
94 port = in6->sin6_port;
95 }
96
97 /* Apply the FNV-1a hash algorithm, using a random seed. */
98 UINT32 hash = 2166136261u ^ g_hashSeed;
99 for (size_t x = 0; x < length; x++)
100 {
101 hash ^= bytes[x];
102 hash *= 16777619u;
103 }
104 hash ^= (UINT32)(port & 0xFF);
105 hash *= 16777619u;
106 hash ^= (UINT32)(port >> 8);
107 hash *= 16777619u;
108 return udplistener_fmix32(hash);
109}
110
111WINPR_ATTR_NODISCARD
112static BOOL udplistener_address_equal(const void* a, const void* b)
113{
114 return udpsocket_address_equal(a, b, sizeof(struct sockaddr_storage));
115}
116
117/* entriesByHash is keyed by cookie hash. For relays, the cookie hash is provided by the
118 * process serving the client and can be arbitrary, so it is seeded like the address hash. */
119WINPR_ATTR_NODISCARD
120static UINT32 udplistener_cookie_hash_hash(const void* key)
121{
122 const BYTE* bytes = key;
123 WINPR_ASSERT(bytes);
124
125 /* FNV-1a hash, seeded with a random value. */
126 UINT32 hash = 2166136261u ^ g_hashSeed;
127 for (size_t x = 0; x < 32; x++)
128 {
129 hash ^= bytes[x];
130 hash *= 16777619u;
131 }
132 return udplistener_fmix32(hash);
133}
134
135WINPR_ATTR_NODISCARD
136static BOOL udplistener_cookie_hash_equal(const void* a, const void* b)
137{
138 WINPR_ASSERT(a);
139 WINPR_ASSERT(b);
140 return memcmp(a, b, 32) == 0;
141}
142
143WINPR_ATTR_NODISCARD
144static wHashTable* udplistener_table_new(HASH_TABLE_HASH_FN hash, OBJECT_EQUALS_FN equal)
145{
146 wHashTable* table = HashTable_New(FALSE);
147 if (!table)
148 return nullptr;
149 wObject* key = HashTable_KeyObject(table);
150 if (!key || !HashTable_SetHashFunction(table, hash))
151 {
152 HashTable_Free(table);
153 return nullptr;
154 }
155 key->fnObjectEquals = equal;
156 return table;
157}
158
159/* This function assumes the caller holds the listener's lock. */
160static void udplistener_bind_flow(rdpUdpFlow* flow, SOCKET sockfd, const struct sockaddr* addr,
161 size_t addrlen, const udpLocalAddress* local)
162{
163 WINPR_ASSERT(flow);
164 WINPR_ASSERT(addrlen <= sizeof(flow->peer));
165 WINPR_ASSERT(local);
166
167 EnterCriticalSection(&flow->lock);
168 flow->sockfd = sockfd;
169 memcpy(&flow->peer, addr, addrlen);
170 flow->peerLength = addrlen;
171 flow->local = *local;
172 LeaveCriticalSection(&flow->lock);
173}
174
175/* The listener's lock must be held by the caller. */
176static void udplistener_dispatch(freerdp_udp_listener* listener, const udpListenerSocket* sock,
177 const struct sockaddr_storage* addr, size_t addrlen,
178 const udpLocalAddress* local, const BYTE* data, size_t length)
179{
180 WINPR_ASSERT(listener);
181 WINPR_ASSERT(sock);
182 WINPR_ASSERT(addr);
183 WINPR_ASSERT(local);
184 WINPR_ASSERT(data || (length == 0));
185
186 /* RDP-UDP datagrams are never empty; relays use empty messages to signal termination, so
187 * empty datagrams from the network must not reach a flow. */
188 if (length == 0)
189 {
190 WLog_DBG(TAG, "discarding an empty datagram");
191 return;
192 }
193 /* Exceeds maximum size sent by clients or carried by a relay in one piece. */
194 if (length > UDPFLOW_MAX_DATAGRAM)
195 {
196 WLog_DBG(TAG, "discarding a datagram of %" PRIuz " bytes", length);
197 return;
198 }
199
200 udpListenerEntry* entry = HashTable_GetItemValue(listener->entriesByAddress, addr);
201
202 BYTE hash[32] = WINPR_C_ARRAY_INIT;
203 const BOOL hasHash = rdpudp_get_syn_cookie_hash(data, length, hash);
204
205 /* A spoofed SYN could bind a flow to a client's address before the client connects. To
206 * prevent the flow's process from answering as the server or a spoofed SYN from hijacking a
207 * connected client, the listener drops the SYN if the hash doesn't match, forcing the client
208 * to remain on TCP. */
209 if (entry && hasHash && (memcmp(entry->flow->cookieHash, hash, sizeof(hash)) != 0))
210 {
211 /* Use DBG instead of INFO to prevent log flooding by network attackers. */
212 WLog_DBG(TAG, "discarding SYN packet due to cookie hash mismatch with the bound flow");
213 return;
214 }
215
216 if (!entry)
217 {
218 if (!hasHash)
219 {
220 WLog_DBG(TAG, "discarding a datagram from an unrecognized client");
221 return;
222 }
223 entry = HashTable_GetItemValue(listener->entriesByHash, hash);
224 if (!entry || entry->bound ||
225 ((entry->sockfd != INVALID_SOCKET) && (entry->sockfd != sock->sockfd)))
226 {
227 WLog_DBG(TAG,
228 "discarding SYN packet because its cookie hash does not match any session");
229 return;
230 }
231 if (addrlen > sizeof(entry->addr))
232 return;
233 memcpy(&entry->addr, addr, addrlen);
234 entry->addrlen = addrlen;
235 if (!HashTable_Insert(listener->entriesByAddress, &entry->addr, entry))
236 return;
237 entry->bound = TRUE;
238 udplistener_bind_flow(entry->flow, sock->sockfd, (const struct sockaddr*)addr, addrlen,
239 local);
240 }
241
242 rdpUdpFlow* flow = entry->flow;
243 /* The callback runs under the flow's lock, so freerdp_udp_flow_set_receive() waits for it. */
244 EnterCriticalSection(&flow->lock);
245 const BOOL taken = flow->receive ? flow->receive(flow->receiveCustom, data, length)
246 : freerdp_udp_flow_deliver(flow, data, length);
247 LeaveCriticalSection(&flow->lock);
248 if (!taken)
249 WLog_DBG(TAG, "flow is full, dropping a datagram");
250}
251
252BOOL freerdp_udp_listener_check(freerdp_udp_listener* listener)
253{
254 WINPR_ASSERT(listener);
255
256 EnterCriticalSection(&listener->lock);
257 for (size_t x = 0; x < listener->socketCount; x++)
258 {
259 const udpListenerSocket* sock = &listener->sockets[x];
260 (void)WSAResetEvent(sock->event);
261 for (size_t count = 0; count < UDPLISTENER_READ_BUDGET; count++)
262 {
263 struct sockaddr_storage addr = WINPR_C_ARRAY_INIT;
264 int addrlen = WINPR_ASSERTING_INT_CAST(int, sizeof(addr));
265 udpLocalAddress local = WINPR_C_ARRAY_INIT;
266 const int rc = udpsocket_receive(sock, listener->buffer, sizeof(listener->buffer),
267 &addr, &addrlen, &local);
268 if (rc < 0)
269 {
270 /* ICMP errors for previous replies indicate a client has disconnected or is
271 * unreachable. */
272 const int error = WSAGetLastError();
273 if ((error == WSAECONNRESET) || (error == WSAENETRESET))
274 continue;
275 break; /* no more data available */
276 }
277 udplistener_dispatch(listener, sock, &addr, WINPR_ASSERTING_INT_CAST(size_t, addrlen),
278 &local, listener->buffer, WINPR_ASSERTING_INT_CAST(size_t, rc));
279 }
280 }
281 LeaveCriticalSection(&listener->lock);
282 return TRUE;
283}
284
285static void udplistener_close_socket(udpListenerSocket* sock)
286{
287 WINPR_ASSERT(sock);
288 const SOCKET sockfd = sock->sockfd;
289 sock->sockfd = INVALID_SOCKET;
290 closesocket(sockfd);
291 if (!WSACloseEvent(sock->event))
292 WLog_WARN(TAG, "failed to close the socket event");
293}
294
295/* Closes retired sockets. Caller holds the lock, and the listener thread does not wait on
296 * their events: it is the caller, or it is stopped. */
297static void udplistener_close_retired(freerdp_udp_listener* listener)
298{
299 WINPR_ASSERT(listener);
300 for (size_t x = 0; x < listener->retiredCount; x++)
301 udplistener_close_socket(&listener->retired[x]);
302 listener->retiredCount = 0;
303}
304
305WINPR_ATTR_NODISCARD
306static DWORD WINAPI udplistener_thread(LPVOID arg)
307{
308 freerdp_udp_listener* listener = arg;
309 WINPR_ASSERT(listener);
310
311 while (InterlockedCompareExchange(&listener->stop, 0, 0) == 0)
312 {
313 HANDLE events[UDPLISTENER_MAX_SOCKETS + 1] = WINPR_C_ARRAY_INIT;
314 DWORD count = 0;
315 events[count++] = listener->wake;
316 EnterCriticalSection(&listener->lock);
317 (void)ResetEvent(listener->wake);
318 /* udplistener_stop_thread sets stop before wake: a stop that came after the check above
319 * either shows here, or its wake-up comes after the reset and ends the wait */
320 if (InterlockedCompareExchange(&listener->stop, 0, 0) != 0)
321 {
322 LeaveCriticalSection(&listener->lock);
323 break;
324 }
325 /* the last wait set is done with, sockets retired since can go */
326 udplistener_close_retired(listener);
327 for (size_t x = 0; x < listener->socketCount; x++)
328 events[count++] = listener->sockets[x].event;
329 LeaveCriticalSection(&listener->lock);
330
331 if (WaitForMultipleObjects(count, events, FALSE, INFINITE) == WAIT_FAILED)
332 {
333 WLog_ERR(TAG, "UDP listener stopping: wait failed, new clients will use TCP");
334 break;
335 }
336 if (InterlockedCompareExchange(&listener->stop, 0, 0) != 0)
337 break;
338 if (!freerdp_udp_listener_check(listener))
339 {
340 WLog_ERR(TAG, "UDP listener stopped: check failed, new clients will use TCP");
341 break;
342 }
343 }
344
345 ExitThread(0);
346 return 0;
347}
348
349/* This function requires the caller to hold the lock. */
350WINPR_ATTR_NODISCARD
351static BOOL udplistener_add_socket(freerdp_udp_listener* listener, SOCKET sockfd)
352{
353 WINPR_ASSERT(listener);
354
355 if (listener->socketCount >= UDPLISTENER_MAX_SOCKETS)
356 return FALSE;
357
358 struct sockaddr_storage addr = WINPR_C_ARRAY_INIT;
359 int addrlen = WINPR_ASSERTING_INT_CAST(int, sizeof(addr));
360 if (_getsockname(sockfd, (struct sockaddr*)&addr, &addrlen) != 0)
361 return FALSE;
362 /* Flows are bound by address, which only compares for these families: an entry on any
363 * other socket could not be found again to remove it. */
364 int type = 0;
365 int typeLength = sizeof(type);
366 if (((addr.ss_family != AF_INET) && (addr.ss_family != AF_INET6)) ||
367 (_getsockopt(sockfd, SOL_SOCKET, SO_TYPE, (char*)&type, &typeLength) != 0) ||
368 (type != SOCK_DGRAM))
369 {
370 WLog_ERR(TAG, "not a UDP socket");
371 return FALSE;
372 }
373
374 HANDLE event = WSACreateEvent();
375 if (!event)
376 return FALSE;
377 /* This also sets the socket to non-blocking mode. */
378 if (WSAEventSelect(sockfd, event, FD_READ) != 0)
379 {
380 if (!WSACloseEvent(event))
381 WLog_WARN(TAG, "failed to close the socket event");
382 return FALSE;
383 }
384
385 /* Increment count only after the entry is fully initialized to prevent forked children
386 * from seeing a partial entry. */
387 udpListenerSocket* sock = &listener->sockets[listener->socketCount];
388 memset(sock, 0, sizeof(*sock));
389 memcpy(&sock->addr, &addr, sizeof(addr));
390 sock->addrlen = WINPR_ASSERTING_INT_CAST(size_t, addrlen);
391 sock->sockfd = sockfd;
392 sock->event = event;
393 udpsocket_enable_local_address(sock);
394 listener->socketCount++;
395 udpsocket_ignore_icmp_errors(sockfd);
396 (void)SetEvent(listener->wake); /* wake the listener thread to update the wait set */
397 return TRUE;
398}
399
400/* Caller must hold the lock. */
401WINPR_ATTR_NODISCARD
402static BOOL udplistener_open_socket(freerdp_udp_listener* listener, const struct sockaddr* addr,
403 size_t addrlen)
404{
405 WINPR_ASSERT(listener);
406 WINPR_ASSERT(addr);
407
408 SOCKET sockfd = udpsocket_bind(addr, addrlen);
409 if (sockfd == INVALID_SOCKET)
410 return FALSE;
411 if (!udplistener_add_socket(listener, sockfd))
412 {
413 closesocket(sockfd);
414 return FALSE;
415 }
416 WLog_INFO(TAG, "waiting for RDP-UDP connections on %s",
417 (addr->sa_family == AF_INET6) ? "an IPv6 address" : "an IPv4 address");
418 return TRUE;
419}
420
421/* Caller must hold the lock. */
422WINPR_ATTR_NODISCARD
423static BOOL udplistener_open_address(freerdp_udp_listener* listener, const char* address,
424 UINT16 port)
425{
426 WINPR_ASSERT(listener);
427
428 char service[8] = WINPR_C_ARRAY_INIT;
429 if (_snprintf(service, sizeof(service), "%" PRIu16, port) < 0)
430 return FALSE;
431
432 struct addrinfo hints = WINPR_C_ARRAY_INIT;
433 hints.ai_family = AF_UNSPEC;
434 hints.ai_socktype = SOCK_DGRAM;
435 hints.ai_flags = AI_PASSIVE;
436 struct addrinfo* result = nullptr;
437 if (getaddrinfo(address, service, &hints, &result) != 0)
438 return FALSE;
439
440 BOOL opened = FALSE;
441 for (const struct addrinfo* ai = result; ai; ai = ai->ai_next)
442 {
443 if (udplistener_open_socket(listener, ai->ai_addr, ai->ai_addrlen))
444 opened = TRUE;
445 }
446 freeaddrinfo(result);
447 if (!opened)
448 WLog_ERR(TAG, "unable to open a UDP socket on port %" PRIu16, port);
449 return opened;
450}
451
452freerdp_udp_listener* freerdp_udp_listener_new(void)
453{
454 if (!InitOnceExecuteOnce(&g_listenerOnce, udplistener_init, nullptr, nullptr))
455 return nullptr;
456
457 freerdp_udp_listener* listener = calloc(1, sizeof(freerdp_udp_listener));
458 if (!listener)
459 return nullptr;
460 listener->relayWake[0] = INVALID_SOCKET;
461 listener->relayWake[1] = INVALID_SOCKET;
462 if (!InitializeCriticalSectionAndSpinCount(&listener->lock, 4000))
463 {
464 free(listener);
465 return nullptr;
466 }
467 listener->wake = CreateEvent(nullptr, TRUE, FALSE, nullptr);
468 listener->entriesByHash =
469 udplistener_table_new(udplistener_cookie_hash_hash, udplistener_cookie_hash_equal);
470 listener->entriesByAddress =
471 udplistener_table_new(udplistener_address_hash, udplistener_address_equal);
472 if (!listener->wake || !listener->entriesByHash || !listener->entriesByAddress)
473 {
474 HashTable_Free(listener->entriesByAddress);
475 HashTable_Free(listener->entriesByHash);
476 if (listener->wake)
477 (void)CloseHandle(listener->wake);
478 DeleteCriticalSection(&listener->lock);
479 free(listener);
480 return nullptr;
481 }
482 return listener;
483}
484
485BOOL freerdp_udp_listener_open(freerdp_udp_listener* listener, const char* address, UINT16 port)
486{
487 WINPR_ASSERT(listener);
488 EnterCriticalSection(&listener->lock);
489 const BOOL rc = udplistener_open_address(listener, address, port);
490 LeaveCriticalSection(&listener->lock);
491 return rc;
492}
493
494BOOL freerdp_udp_listener_open_from_socket(freerdp_udp_listener* listener, int fd)
495{
496 WINPR_ASSERT(listener);
497 EnterCriticalSection(&listener->lock);
498 const BOOL rc = udplistener_add_socket(listener, (SOCKET)fd);
499 LeaveCriticalSection(&listener->lock);
500 /* Only for sockets owned by the listener; on failure, the caller retains ownership of fd */
501 if (rc)
502 udpsocket_set_no_inherit((SOCKET)fd);
503 return rc;
504}
505
506DWORD freerdp_udp_listener_get_event_handles(freerdp_udp_listener* listener, HANDLE* events,
507 DWORD count)
508{
509 WINPR_ASSERT(listener);
510 WINPR_ASSERT(events);
511
512 DWORD used = 0;
513 EnterCriticalSection(&listener->lock);
514 if (listener->socketCount <= count)
515 {
516 for (size_t x = 0; x < listener->socketCount; x++)
517 events[used++] = listener->sockets[x].event;
518 }
519 LeaveCriticalSection(&listener->lock);
520 return used;
521}
522
523BOOL freerdp_udp_listener_start(freerdp_udp_listener* listener)
524{
525 WINPR_ASSERT(listener);
526 /* A thread that ended by itself (its wait failed) is replaced, or nobody would read the
527 * sockets while this still reported a running thread. */
528 if (listener->thread && (WaitForSingleObject(listener->thread, 0) == WAIT_OBJECT_0))
529 {
530 WLog_WARN(TAG, "the listener thread has ended, starting a new one");
531 (void)CloseHandle(listener->thread);
532 listener->thread = nullptr;
533 }
534 if (listener->thread)
535 return TRUE;
536 if (InterlockedCompareExchange(&listener->stop, 0, 1) != 0)
537 WLog_DBG(TAG, "restarting the listener thread");
538 listener->thread = CreateThread(nullptr, 0, udplistener_thread, listener, 0, nullptr);
539 return listener->thread != nullptr;
540}
541
542static void udplistener_stop_thread(freerdp_udp_listener* listener)
543{
544 WINPR_ASSERT(listener);
545 if (!listener->thread)
546 return;
547 /* Avoid InterlockedExchange; WinPR reads the old value non-atomically */
548 InterlockedIncrement(&listener->stop);
549 (void)SetEvent(listener->wake);
550 (void)WaitForSingleObject(listener->thread, INFINITE);
551 (void)CloseHandle(listener->thread);
552 listener->thread = nullptr;
553}
554
555WINPR_ATTR_NODISCARD
556static BOOL udplistener_unbind_socket(WINPR_ATTR_UNUSED const void* key, void* value,
557 WINPR_ATTR_UNUSED void* arg)
558{
559 udpListenerEntry* entry = value;
560 WINPR_ASSERT(entry);
561 EnterCriticalSection(&entry->flow->lock);
562 entry->flow->sockfd = INVALID_SOCKET;
563 LeaveCriticalSection(&entry->flow->lock);
564 return TRUE;
565}
566
567/* Thread must not be running. Detaches all flows from sockets before closing them. */
568static void udplistener_close_sockets(freerdp_udp_listener* listener)
569{
570 WINPR_ASSERT(listener);
571
572 EnterCriticalSection(&listener->lock);
573 if (!HashTable_Foreach(listener->entriesByHash, udplistener_unbind_socket, nullptr))
574 WLog_WARN(TAG, "failed to release sockets for all flows");
575 /* Invalidate the entry before closing the socket; see close_after_fork */
576 for (size_t x = 0; x < listener->socketCount; x++)
577 udplistener_close_socket(&listener->sockets[x]);
578 listener->socketCount = 0;
579 udplistener_close_retired(listener);
580 LeaveCriticalSection(&listener->lock);
581}
582
583/* Releases the memory once the listener was freed and its last flow removed. */
584static void udplistener_release(freerdp_udp_listener* listener)
585{
586 WINPR_ASSERT(listener);
587 HashTable_Free(listener->entriesByAddress);
588 HashTable_Free(listener->entriesByHash);
589 (void)CloseHandle(listener->wake);
590 DeleteCriticalSection(&listener->lock);
591 free(listener);
592}
593
594void freerdp_udp_listener_close_after_fork(freerdp_udp_listener* listener)
595{
596 const BOOL shared = !listener || (listener == g_listener);
597 if (!listener)
598 listener = g_listener;
599 if (shared)
600 {
601 /* Parent may hold the lock and the listener thread is not inherited by the child; the child
602 * must initialize a new process-wide listener. */
603 g_listener = nullptr;
604 if (!InitializeCriticalSectionAndSpinCount(&g_listenerLock, 4000))
605 WLog_WARN(TAG, "unable to reset the process-wide listener lock");
606 }
607 if (!listener)
608 return;
609
610 /* Parent continues using these sockets; close local copies without sending messages or
611 * shutdown. */
612 for (size_t x = 0; x < listener->socketCount; x++)
613 {
614 const SOCKET sockfd = listener->sockets[x].sockfd;
615 listener->sockets[x].sockfd = INVALID_SOCKET;
616 if (sockfd != INVALID_SOCKET)
617 closesocket(sockfd);
618 }
619 for (size_t x = 0; x < listener->retiredCount; x++)
620 {
621 const SOCKET sockfd = listener->retired[x].sockfd;
622 listener->retired[x].sockfd = INVALID_SOCKET;
623 if (sockfd != INVALID_SOCKET)
624 closesocket(sockfd);
625 }
626 udplistener_relays_close_after_fork(listener);
627}
628
629void freerdp_udp_listener_free(freerdp_udp_listener* listener)
630{
631 if (!listener)
632 return;
633
634 udplistener_stop_thread(listener);
635 udplistener_stop_relays(listener);
636 udplistener_close_sockets(listener);
637
638 /* Flows still registered keep their entries and their pointer to the listener, so a peer
639 * may free its flow at any time; the last one removed releases the listener. */
640 EnterCriticalSection(&listener->lock);
641 listener->freed = TRUE;
642 const BOOL release = (HashTable_Count(listener->entriesByHash) == 0);
643 LeaveCriticalSection(&listener->lock);
644 if (release)
645 udplistener_release(listener);
646}
647
648BOOL udplistener_add_flow(freerdp_udp_listener* listener, rdpUdpFlow* flow, SOCKET sockfd)
649{
650 WINPR_ASSERT(listener);
651 WINPR_ASSERT(flow);
652
653 udpListenerEntry* entry = calloc(1, sizeof(udpListenerEntry));
654 if (!entry)
655 return FALSE;
656 entry->flow = flow;
657 entry->sockfd = sockfd;
658
659 BOOL rc = FALSE;
660 EnterCriticalSection(&listener->lock);
661 if (!flow->listener && !HashTable_Contains(listener->entriesByHash, flow->cookieHash) &&
662 HashTable_Insert(listener->entriesByHash, flow->cookieHash, entry))
663 {
664 flow->listener = listener;
665 rc = TRUE;
666 }
667 LeaveCriticalSection(&listener->lock);
668 if (!rc)
669 free(entry);
670 // NOLINTNEXTLINE(clang-analyzer-unix.Malloc): entriesByHash owns entry
671 return rc;
672}
673
674BOOL freerdp_udp_listener_add_flow(freerdp_udp_listener* listener, rdpUdpFlow* flow)
675{
676 return udplistener_add_flow(listener, flow, INVALID_SOCKET);
677}
678
679typedef struct
680{
681 const freerdp_udp_listener* listener;
682 BOOL used[UDPLISTENER_MAX_SOCKETS];
683} udpSocketUse;
684
685WINPR_ATTR_NODISCARD
686static BOOL udplistener_mark_socket_use(WINPR_ATTR_UNUSED const void* key, void* value, void* arg)
687{
688 const udpListenerEntry* entry = value;
689 udpSocketUse* use = arg;
690 WINPR_ASSERT(entry);
691 WINPR_ASSERT(use);
692 for (size_t x = 0; x < use->listener->socketCount; x++)
693 {
694 if (use->listener->sockets[x].sockfd == entry->sockfd)
695 use->used[x] = TRUE;
696 }
697 return TRUE;
698}
699
700/* Finds sockets not associated with any registered flow. Flows registered with
701 * INVALID_SOCKET do not keep any alive. Caller must hold the lock. */
702WINPR_ATTR_NODISCARD
703static BOOL udplistener_find_unused_sockets(const freerdp_udp_listener* listener, udpSocketUse* use)
704{
705 WINPR_ASSERT(listener);
706 WINPR_ASSERT(use);
707 memset(use, 0, sizeof(*use));
708 use->listener = listener;
709 BOOL unused = FALSE;
710 if (!HashTable_Foreach(listener->entriesByHash, udplistener_mark_socket_use, use))
711 return FALSE;
712 for (size_t x = 0; x < listener->socketCount; x++)
713 {
714 if (!use->used[x])
715 unused = TRUE;
716 }
717 return unused;
718}
719
720/* Caller must hold the lock. A running listener thread may wait on these events: the sockets
721 * are retired and the thread, woken, closes them when it builds its next wait set. Without a
722 * thread they are closed now. */
723static void udplistener_close_unused_sockets(freerdp_udp_listener* listener,
724 const udpSocketUse* use)
725{
726 WINPR_ASSERT(listener);
727 WINPR_ASSERT(use);
728 size_t kept = 0;
729 for (size_t x = 0; x < listener->socketCount; x++)
730 {
731 if (use->used[x])
732 {
733 listener->sockets[kept++] = listener->sockets[x];
734 continue;
735 }
736 if (!listener->thread)
737 udplistener_close_socket(&listener->sockets[x]);
738 else if (listener->retiredCount < UDPLISTENER_MAX_SOCKETS)
739 listener->retired[listener->retiredCount++] = listener->sockets[x];
740 else /* the thread may wait on it: it stays open, a later removal retires it */
741 listener->sockets[kept++] = listener->sockets[x];
742 }
743 listener->socketCount = kept;
744 if (listener->thread)
745 (void)SetEvent(listener->wake);
746}
747
748void freerdp_udp_listener_remove_flow(freerdp_udp_listener* listener, rdpUdpFlow* flow)
749{
750 WINPR_ASSERT(listener);
751 WINPR_ASSERT(flow);
752
753 EnterCriticalSection(&listener->lock);
754 udpListenerEntry* entry = HashTable_GetItemValue(listener->entriesByHash, flow->cookieHash);
755 if (entry && (entry->flow == flow))
756 {
757 if (entry->bound && !HashTable_Remove(listener->entriesByAddress, &entry->addr))
758 WLog_WARN(TAG, "bound flow is missing an address");
759 if (!HashTable_Remove(listener->entriesByHash, flow->cookieHash))
760 WLog_WARN(TAG, "failed to remove flow");
761 free(entry);
762
763 /* Socket is owned by the listener and can be closed after this function returns. */
764 EnterCriticalSection(&flow->lock);
765 flow->sockfd = INVALID_SOCKET;
766 LeaveCriticalSection(&flow->lock);
767 }
768 /* Flows registered with other listeners remain unaffected. */
769 if (flow->listener == listener)
770 flow->listener = nullptr;
771 const BOOL shared = listener->shared;
772 const BOOL release = listener->freed && (HashTable_Count(listener->entriesByHash) == 0);
773 LeaveCriticalSection(&listener->lock);
774
775 /* the process-wide listener is never freed, so it does not get here */
776 if (release)
777 {
778 udplistener_release(listener);
779 return;
780 }
781 if (!shared)
782 return;
783
784 /* Close the thread and sockets when the last flow is gone. Sockets not used by any flow are
785 * also closed, as a host with changing addresses may exceed UDPLISTENER_MAX_SOCKETS over time.
786 */
787 udpSocketUse use = WINPR_C_ARRAY_INIT;
788 EnterCriticalSection(&g_listenerLock);
789 EnterCriticalSection(&listener->lock);
790 const BOOL empty = (HashTable_Count(listener->entriesByHash) == 0);
791 const BOOL unused = !empty && udplistener_find_unused_sockets(listener, &use);
792 LeaveCriticalSection(&listener->lock);
793 if (empty)
794 {
795 udplistener_stop_thread(listener);
796 udplistener_close_sockets(listener);
797 WLog_DBG(TAG, "no more sessions are waiting for RDP-UDP, closing the UDP sockets");
798 }
799 else if (unused)
800 {
801 /* The thread keeps running: stopping and restarting it would leave the sessions on
802 * UDP without a reader if the restart failed. */
803 EnterCriticalSection(&listener->lock);
804 if (udplistener_find_unused_sockets(listener, &use))
805 udplistener_close_unused_sockets(listener, &use);
806 LeaveCriticalSection(&listener->lock);
807 }
808 LeaveCriticalSection(&g_listenerLock);
809}
810
811BOOL udplistener_add_flow_on_address(const struct sockaddr* addr, size_t addrlen, rdpUdpFlow* flow)
812{
813 WINPR_ASSERT(addr);
814 WINPR_ASSERT(flow);
815
816 if ((addrlen > sizeof(struct sockaddr_storage)) ||
817 !InitOnceExecuteOnce(&g_listenerOnce, udplistener_init, nullptr, nullptr))
818 return FALSE;
819
820 struct sockaddr_storage local = WINPR_C_ARRAY_INIT;
821 size_t localLength = 0;
822 udpsocket_unmap_address(addr, addrlen, &local, &localLength);
823
824 BOOL rc = FALSE;
825 EnterCriticalSection(&g_listenerLock);
826 if (!g_listener)
827 {
828 g_listener = freerdp_udp_listener_new();
829 if (g_listener)
830 g_listener->shared = TRUE;
831 }
832 if (g_listener)
833 {
834 SOCKET sockfd = INVALID_SOCKET;
835 EnterCriticalSection(&g_listener->lock);
836 for (size_t x = 0; (sockfd == INVALID_SOCKET) && (x < g_listener->socketCount); x++)
837 {
838 const udpListenerSocket* sock = &g_listener->sockets[x];
839 if (udpsocket_address_equal(&sock->addr, (const struct sockaddr*)&local, localLength))
840 sockfd = sock->sockfd;
841 }
842 /* A socket retired a moment ago is still bound until the listener thread closes it,
843 * and a second bind to its address would fail: it is taken back into use. The thread
844 * may still have its event in the wait set, which does no harm. */
845 for (size_t x = 0; (sockfd == INVALID_SOCKET) && (x < g_listener->retiredCount) &&
846 (g_listener->socketCount < UDPLISTENER_MAX_SOCKETS);
847 x++)
848 {
849 const udpListenerSocket* sock = &g_listener->retired[x];
850 if (!udpsocket_address_equal(&sock->addr, (const struct sockaddr*)&local, localLength))
851 continue;
852 sockfd = sock->sockfd;
853 g_listener->sockets[g_listener->socketCount++] = *sock;
854 g_listener->retired[x] = g_listener->retired[--g_listener->retiredCount];
855 (void)SetEvent(g_listener->wake);
856 }
857 if ((sockfd == INVALID_SOCKET) &&
858 udplistener_open_socket(g_listener, (const struct sockaddr*)&local, localLength))
859 sockfd = g_listener->sockets[g_listener->socketCount - 1].sockfd;
860 LeaveCriticalSection(&g_listener->lock);
861
862 rc = (sockfd != INVALID_SOCKET) && udplistener_add_flow(g_listener, flow, sockfd) &&
863 freerdp_udp_listener_start(g_listener);
864 }
865 LeaveCriticalSection(&g_listenerLock);
866 if (!rc && flow->listener)
867 freerdp_udp_listener_remove_flow(flow->listener, flow);
868 return rc;
869}
This struct contains function pointer to initialize/free objects.
Definition collections.h:52