20#include <winpr/assert.h>
21#include <winpr/cast.h>
22#include <winpr/collections.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>
34#include <freerdp/log.h>
37#include "udplistener_internal.h"
39#define TAG FREERDP_TAG("core.udplistener")
41static freerdp_udp_listener* g_listener;
42static CRITICAL_SECTION g_listenerLock;
43static INIT_ONCE g_listenerOnce = INIT_ONCE_STATIC_INIT;
46static UINT32 g_hashSeed;
49static BOOL CALLBACK udplistener_init(WINPR_ATTR_UNUSED PINIT_ONCE once,
50 WINPR_ATTR_UNUSED PVOID param,
51 WINPR_ATTR_UNUSED PVOID* context)
53 if (winpr_RAND(&g_hashSeed,
sizeof(g_hashSeed)) < 0)
55 return InitializeCriticalSectionAndSpinCount(&g_listenerLock, 4000);
62static UINT32 udplistener_fmix32(UINT32 hash)
74static UINT32 udplistener_address_hash(
const void* key)
76 const struct sockaddr_storage* addr = key;
79 const BYTE* bytes =
nullptr;
82 if (addr->ss_family == AF_INET)
84 const struct sockaddr_in* in = (
const struct sockaddr_in*)addr;
85 bytes = (
const BYTE*)&in->sin_addr;
86 length =
sizeof(in->sin_addr);
89 else if (addr->ss_family == AF_INET6)
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;
98 UINT32 hash = 2166136261u ^ g_hashSeed;
99 for (
size_t x = 0; x < length; x++)
104 hash ^= (UINT32)(port & 0xFF);
106 hash ^= (UINT32)(port >> 8);
108 return udplistener_fmix32(hash);
112static BOOL udplistener_address_equal(
const void* a,
const void* b)
114 return udpsocket_address_equal(a, b,
sizeof(
struct sockaddr_storage));
120static UINT32 udplistener_cookie_hash_hash(
const void* key)
122 const BYTE* bytes = key;
126 UINT32 hash = 2166136261u ^ g_hashSeed;
127 for (
size_t x = 0; x < 32; x++)
132 return udplistener_fmix32(hash);
136static BOOL udplistener_cookie_hash_equal(
const void* a,
const void* b)
140 return memcmp(a, b, 32) == 0;
144static wHashTable* udplistener_table_new(HASH_TABLE_HASH_FN hash, OBJECT_EQUALS_FN equal)
146 wHashTable* table = HashTable_New(FALSE);
149 wObject* key = HashTable_KeyObject(table);
150 if (!key || !HashTable_SetHashFunction(table, hash))
152 HashTable_Free(table);
155 key->fnObjectEquals = equal;
160static void udplistener_bind_flow(rdpUdpFlow* flow, SOCKET sockfd,
const struct sockaddr* addr,
164 WINPR_ASSERT(addrlen <=
sizeof(flow->peer));
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);
176static void udplistener_dispatch(freerdp_udp_listener* listener,
const udpListenerSocket* sock,
177 const struct sockaddr_storage* addr,
size_t addrlen,
180 WINPR_ASSERT(listener);
184 WINPR_ASSERT(data || (length == 0));
190 WLog_DBG(TAG,
"discarding an empty datagram");
194 if (length > UDPFLOW_MAX_DATAGRAM)
196 WLog_DBG(TAG,
"discarding a datagram of %" PRIuz
" bytes", length);
200 udpListenerEntry* entry = HashTable_GetItemValue(listener->entriesByAddress, addr);
202 BYTE hash[32] = WINPR_C_ARRAY_INIT;
203 const BOOL hasHash = rdpudp_get_syn_cookie_hash(data, length, hash);
209 if (entry && hasHash && (memcmp(entry->flow->cookieHash, hash,
sizeof(hash)) != 0))
212 WLog_DBG(TAG,
"discarding SYN packet due to cookie hash mismatch with the bound flow");
220 WLog_DBG(TAG,
"discarding a datagram from an unrecognized client");
223 entry = HashTable_GetItemValue(listener->entriesByHash, hash);
224 if (!entry || entry->bound ||
225 ((entry->sockfd != INVALID_SOCKET) && (entry->sockfd != sock->sockfd)))
228 "discarding SYN packet because its cookie hash does not match any session");
231 if (addrlen >
sizeof(entry->addr))
233 memcpy(&entry->addr, addr, addrlen);
234 entry->addrlen = addrlen;
235 if (!HashTable_Insert(listener->entriesByAddress, &entry->addr, entry))
238 udplistener_bind_flow(entry->flow, sock->sockfd, (
const struct sockaddr*)addr, addrlen,
242 rdpUdpFlow* flow = entry->flow;
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);
249 WLog_DBG(TAG,
"flow is full, dropping a datagram");
252BOOL freerdp_udp_listener_check(freerdp_udp_listener* listener)
254 WINPR_ASSERT(listener);
256 EnterCriticalSection(&listener->lock);
257 for (
size_t x = 0; x < listener->socketCount; x++)
260 (void)WSAResetEvent(sock->event);
261 for (
size_t count = 0; count < UDPLISTENER_READ_BUDGET; count++)
263 struct sockaddr_storage addr = WINPR_C_ARRAY_INIT;
264 int addrlen = WINPR_ASSERTING_INT_CAST(
int,
sizeof(addr));
266 const int rc = udpsocket_receive(sock, listener->buffer,
sizeof(listener->buffer),
267 &addr, &addrlen, &local);
272 const int error = WSAGetLastError();
273 if ((error == WSAECONNRESET) || (error == WSAENETRESET))
277 udplistener_dispatch(listener, sock, &addr, WINPR_ASSERTING_INT_CAST(
size_t, addrlen),
278 &local, listener->buffer, WINPR_ASSERTING_INT_CAST(
size_t, rc));
281 LeaveCriticalSection(&listener->lock);
288 const SOCKET sockfd = sock->sockfd;
289 sock->sockfd = INVALID_SOCKET;
291 if (!WSACloseEvent(sock->event))
292 WLog_WARN(TAG,
"failed to close the socket event");
297static void udplistener_close_retired(freerdp_udp_listener* listener)
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;
306static DWORD WINAPI udplistener_thread(LPVOID arg)
308 freerdp_udp_listener* listener = arg;
309 WINPR_ASSERT(listener);
311 while (InterlockedCompareExchange(&listener->stop, 0, 0) == 0)
313 HANDLE events[UDPLISTENER_MAX_SOCKETS + 1] = WINPR_C_ARRAY_INIT;
315 events[count++] = listener->wake;
316 EnterCriticalSection(&listener->lock);
317 (void)ResetEvent(listener->wake);
320 if (InterlockedCompareExchange(&listener->stop, 0, 0) != 0)
322 LeaveCriticalSection(&listener->lock);
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);
331 if (WaitForMultipleObjects(count, events, FALSE, INFINITE) == WAIT_FAILED)
333 WLog_ERR(TAG,
"UDP listener stopping: wait failed, new clients will use TCP");
336 if (InterlockedCompareExchange(&listener->stop, 0, 0) != 0)
338 if (!freerdp_udp_listener_check(listener))
340 WLog_ERR(TAG,
"UDP listener stopped: check failed, new clients will use TCP");
351static BOOL udplistener_add_socket(freerdp_udp_listener* listener, SOCKET sockfd)
353 WINPR_ASSERT(listener);
355 if (listener->socketCount >= UDPLISTENER_MAX_SOCKETS)
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)
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))
370 WLog_ERR(TAG,
"not a UDP socket");
374 HANDLE
event = WSACreateEvent();
378 if (WSAEventSelect(sockfd, event, FD_READ) != 0)
380 if (!WSACloseEvent(event))
381 WLog_WARN(TAG,
"failed to close the socket event");
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;
393 udpsocket_enable_local_address(sock);
394 listener->socketCount++;
395 udpsocket_ignore_icmp_errors(sockfd);
396 (void)SetEvent(listener->wake);
402static BOOL udplistener_open_socket(freerdp_udp_listener* listener,
const struct sockaddr* addr,
405 WINPR_ASSERT(listener);
408 SOCKET sockfd = udpsocket_bind(addr, addrlen);
409 if (sockfd == INVALID_SOCKET)
411 if (!udplistener_add_socket(listener, sockfd))
416 WLog_INFO(TAG,
"waiting for RDP-UDP connections on %s",
417 (addr->sa_family == AF_INET6) ?
"an IPv6 address" :
"an IPv4 address");
423static BOOL udplistener_open_address(freerdp_udp_listener* listener,
const char* address,
426 WINPR_ASSERT(listener);
428 char service[8] = WINPR_C_ARRAY_INIT;
429 if (_snprintf(service,
sizeof(service),
"%" PRIu16, port) < 0)
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)
441 for (
const struct addrinfo* ai = result; ai; ai = ai->ai_next)
443 if (udplistener_open_socket(listener, ai->ai_addr, ai->ai_addrlen))
446 freeaddrinfo(result);
448 WLog_ERR(TAG,
"unable to open a UDP socket on port %" PRIu16, port);
452freerdp_udp_listener* freerdp_udp_listener_new(
void)
454 if (!InitOnceExecuteOnce(&g_listenerOnce, udplistener_init,
nullptr,
nullptr))
457 freerdp_udp_listener* listener = calloc(1,
sizeof(freerdp_udp_listener));
460 listener->relayWake[0] = INVALID_SOCKET;
461 listener->relayWake[1] = INVALID_SOCKET;
462 if (!InitializeCriticalSectionAndSpinCount(&listener->lock, 4000))
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)
474 HashTable_Free(listener->entriesByAddress);
475 HashTable_Free(listener->entriesByHash);
477 (void)CloseHandle(listener->wake);
478 DeleteCriticalSection(&listener->lock);
485BOOL freerdp_udp_listener_open(freerdp_udp_listener* listener,
const char* address, UINT16 port)
487 WINPR_ASSERT(listener);
488 EnterCriticalSection(&listener->lock);
489 const BOOL rc = udplistener_open_address(listener, address, port);
490 LeaveCriticalSection(&listener->lock);
494BOOL freerdp_udp_listener_open_from_socket(freerdp_udp_listener* listener,
int fd)
496 WINPR_ASSERT(listener);
497 EnterCriticalSection(&listener->lock);
498 const BOOL rc = udplistener_add_socket(listener, (SOCKET)fd);
499 LeaveCriticalSection(&listener->lock);
502 udpsocket_set_no_inherit((SOCKET)fd);
506DWORD freerdp_udp_listener_get_event_handles(freerdp_udp_listener* listener, HANDLE* events,
509 WINPR_ASSERT(listener);
510 WINPR_ASSERT(events);
513 EnterCriticalSection(&listener->lock);
514 if (listener->socketCount <= count)
516 for (
size_t x = 0; x < listener->socketCount; x++)
517 events[used++] = listener->sockets[x].event;
519 LeaveCriticalSection(&listener->lock);
523BOOL freerdp_udp_listener_start(freerdp_udp_listener* listener)
525 WINPR_ASSERT(listener);
528 if (listener->thread && (WaitForSingleObject(listener->thread, 0) == WAIT_OBJECT_0))
530 WLog_WARN(TAG,
"the listener thread has ended, starting a new one");
531 (void)CloseHandle(listener->thread);
532 listener->thread =
nullptr;
534 if (listener->thread)
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;
542static void udplistener_stop_thread(freerdp_udp_listener* listener)
544 WINPR_ASSERT(listener);
545 if (!listener->thread)
548 InterlockedIncrement(&listener->stop);
549 (void)SetEvent(listener->wake);
550 (void)WaitForSingleObject(listener->thread, INFINITE);
551 (void)CloseHandle(listener->thread);
552 listener->thread =
nullptr;
556static BOOL udplistener_unbind_socket(WINPR_ATTR_UNUSED
const void* key,
void* value,
557 WINPR_ATTR_UNUSED
void* arg)
561 EnterCriticalSection(&entry->flow->lock);
562 entry->flow->sockfd = INVALID_SOCKET;
563 LeaveCriticalSection(&entry->flow->lock);
568static void udplistener_close_sockets(freerdp_udp_listener* listener)
570 WINPR_ASSERT(listener);
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");
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);
584static void udplistener_release(freerdp_udp_listener* listener)
586 WINPR_ASSERT(listener);
587 HashTable_Free(listener->entriesByAddress);
588 HashTable_Free(listener->entriesByHash);
589 (void)CloseHandle(listener->wake);
590 DeleteCriticalSection(&listener->lock);
594void freerdp_udp_listener_close_after_fork(freerdp_udp_listener* listener)
596 const BOOL shared = !listener || (listener == g_listener);
598 listener = g_listener;
603 g_listener =
nullptr;
604 if (!InitializeCriticalSectionAndSpinCount(&g_listenerLock, 4000))
605 WLog_WARN(TAG,
"unable to reset the process-wide listener lock");
612 for (
size_t x = 0; x < listener->socketCount; x++)
614 const SOCKET sockfd = listener->sockets[x].sockfd;
615 listener->sockets[x].sockfd = INVALID_SOCKET;
616 if (sockfd != INVALID_SOCKET)
619 for (
size_t x = 0; x < listener->retiredCount; x++)
621 const SOCKET sockfd = listener->retired[x].sockfd;
622 listener->retired[x].sockfd = INVALID_SOCKET;
623 if (sockfd != INVALID_SOCKET)
626 udplistener_relays_close_after_fork(listener);
629void freerdp_udp_listener_free(freerdp_udp_listener* listener)
634 udplistener_stop_thread(listener);
635 udplistener_stop_relays(listener);
636 udplistener_close_sockets(listener);
640 EnterCriticalSection(&listener->lock);
641 listener->freed = TRUE;
642 const BOOL release = (HashTable_Count(listener->entriesByHash) == 0);
643 LeaveCriticalSection(&listener->lock);
645 udplistener_release(listener);
648BOOL udplistener_add_flow(freerdp_udp_listener* listener, rdpUdpFlow* flow, SOCKET sockfd)
650 WINPR_ASSERT(listener);
657 entry->sockfd = sockfd;
660 EnterCriticalSection(&listener->lock);
661 if (!flow->listener && !HashTable_Contains(listener->entriesByHash, flow->cookieHash) &&
662 HashTable_Insert(listener->entriesByHash, flow->cookieHash, entry))
664 flow->listener = listener;
667 LeaveCriticalSection(&listener->lock);
674BOOL freerdp_udp_listener_add_flow(freerdp_udp_listener* listener, rdpUdpFlow* flow)
676 return udplistener_add_flow(listener, flow, INVALID_SOCKET);
681 const freerdp_udp_listener* listener;
682 BOOL used[UDPLISTENER_MAX_SOCKETS];
686static BOOL udplistener_mark_socket_use(WINPR_ATTR_UNUSED
const void* key,
void* value,
void* arg)
689 udpSocketUse* use = arg;
692 for (
size_t x = 0; x < use->listener->socketCount; x++)
694 if (use->listener->sockets[x].sockfd == entry->sockfd)
703static BOOL udplistener_find_unused_sockets(
const freerdp_udp_listener* listener, udpSocketUse* use)
705 WINPR_ASSERT(listener);
707 memset(use, 0,
sizeof(*use));
708 use->listener = listener;
710 if (!HashTable_Foreach(listener->entriesByHash, udplistener_mark_socket_use, use))
712 for (
size_t x = 0; x < listener->socketCount; x++)
723static void udplistener_close_unused_sockets(freerdp_udp_listener* listener,
724 const udpSocketUse* use)
726 WINPR_ASSERT(listener);
729 for (
size_t x = 0; x < listener->socketCount; x++)
733 listener->sockets[kept++] = listener->sockets[x];
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];
741 listener->sockets[kept++] = listener->sockets[x];
743 listener->socketCount = kept;
744 if (listener->thread)
745 (void)SetEvent(listener->wake);
748void freerdp_udp_listener_remove_flow(freerdp_udp_listener* listener, rdpUdpFlow* flow)
750 WINPR_ASSERT(listener);
753 EnterCriticalSection(&listener->lock);
754 udpListenerEntry* entry = HashTable_GetItemValue(listener->entriesByHash, flow->cookieHash);
755 if (entry && (entry->flow == flow))
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");
764 EnterCriticalSection(&flow->lock);
765 flow->sockfd = INVALID_SOCKET;
766 LeaveCriticalSection(&flow->lock);
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);
778 udplistener_release(listener);
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);
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");
803 EnterCriticalSection(&listener->lock);
804 if (udplistener_find_unused_sockets(listener, &use))
805 udplistener_close_unused_sockets(listener, &use);
806 LeaveCriticalSection(&listener->lock);
808 LeaveCriticalSection(&g_listenerLock);
811BOOL udplistener_add_flow_on_address(
const struct sockaddr* addr,
size_t addrlen, rdpUdpFlow* flow)
816 if ((addrlen >
sizeof(
struct sockaddr_storage)) ||
817 !InitOnceExecuteOnce(&g_listenerOnce, udplistener_init,
nullptr,
nullptr))
820 struct sockaddr_storage local = WINPR_C_ARRAY_INIT;
821 size_t localLength = 0;
822 udpsocket_unmap_address(addr, addrlen, &local, &localLength);
825 EnterCriticalSection(&g_listenerLock);
828 g_listener = freerdp_udp_listener_new();
830 g_listener->shared = TRUE;
834 SOCKET sockfd = INVALID_SOCKET;
835 EnterCriticalSection(&g_listener->lock);
836 for (
size_t x = 0; (sockfd == INVALID_SOCKET) && (x < g_listener->socketCount); x++)
839 if (udpsocket_address_equal(&sock->addr, (
const struct sockaddr*)&local, localLength))
840 sockfd = sock->sockfd;
845 for (
size_t x = 0; (sockfd == INVALID_SOCKET) && (x < g_listener->retiredCount) &&
846 (g_listener->socketCount < UDPLISTENER_MAX_SOCKETS);
850 if (!udpsocket_address_equal(&sock->addr, (
const struct sockaddr*)&local, localLength))
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);
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);
862 rc = (sockfd != INVALID_SOCKET) && udplistener_add_flow(g_listener, flow, sockfd) &&
863 freerdp_udp_listener_start(g_listener);
865 LeaveCriticalSection(&g_listenerLock);
866 if (!rc && flow->listener)
867 freerdp_udp_listener_remove_flow(flow->listener, flow);
This struct contains function pointer to initialize/free objects.