summaryrefslogtreecommitdiffstats
path: root/src/VBox/Runtime/r3/udp.cpp
blob: 2ed12047b5342e01e76aeb33a808b5d9f9e4e8ea (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
/* $Id: udp.cpp $ */
/** @file
 * IPRT - UDP/IP.
 */

/*
 * Copyright (C) 2006-2023 Oracle and/or its affiliates.
 *
 * This file is part of VirtualBox base platform packages, as
 * available from https://www.virtualbox.org.
 *
 * This program is free software; you can redistribute it and/or
 * modify it under the terms of the GNU General Public License
 * as published by the Free Software Foundation, in version 3 of the
 * License.
 *
 * This program is distributed in the hope that it will be useful, but
 * WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 * General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with this program; if not, see <https://www.gnu.org/licenses>.
 *
 * The contents of this file may alternatively be used under the terms
 * of the Common Development and Distribution License Version 1.0
 * (CDDL), a copy of it is provided in the "COPYING.CDDL" file included
 * in the VirtualBox distribution, in which case the provisions of the
 * CDDL are applicable instead of those of the GPL.
 *
 * You may elect to license modified versions of this file under the
 * terms and conditions of either the GPL or the CDDL or both.
 *
 * SPDX-License-Identifier: GPL-3.0-only OR CDDL-1.0
 */


/*********************************************************************************************************************************
*   Header Files                                                                                                                 *
*********************************************************************************************************************************/
#ifdef RT_OS_WINDOWS
# include <iprt/win/winsock2.h>
#else
# include <sys/types.h>
# include <sys/socket.h>
# include <errno.h>
# include <netinet/in.h>
# include <netinet/udp.h>
# include <arpa/inet.h>
# include <netdb.h>
#endif
#include <limits.h>

#include "internal/iprt.h"
#include <iprt/udp.h>

#include <iprt/asm.h>
#include <iprt/assert.h>
#include <iprt/err.h>
#include <iprt/mempool.h>
#include <iprt/mem.h>
#include <iprt/string.h>
#include <iprt/socket.h>
#include <iprt/thread.h>
#include <iprt/time.h>

#include "internal/magics.h"
#include "internal/socket.h"


/*********************************************************************************************************************************
*   Defined Constants And Macros                                                                                                 *
*********************************************************************************************************************************/
/* fixup backlevel OSes. */
#if defined(RT_OS_OS2) || defined(RT_OS_WINDOWS)
# define socklen_t              int
#endif


/*********************************************************************************************************************************
*   Structures and Typedefs                                                                                                      *
*********************************************************************************************************************************/
/**
 * UDP Server state.
 */
typedef enum RTUDPSERVERSTATE
{
    /** Invalid. */
    RTUDPSERVERSTATE_INVALID = 0,
    /** Created. */
    RTUDPSERVERSTATE_CREATED,
    /** Thread for incoming datagrams is starting up. */
    RTUDPSERVERSTATE_STARTING,
    /** Waiting for incoming datagrams. */
    RTUDPSERVERSTATE_WAITING,
    /** Handling an incoming datagram. */
    RTUDPSERVERSTATE_RECEIVING,
    /** Thread terminating. */
    RTUDPSERVERSTATE_STOPPING,
    /** Thread terminated. */
    RTUDPSERVERSTATE_STOPPED,
    /** Final cleanup before being unusable. */
    RTUDPSERVERSTATE_DESTROYING
} RTUDPSERVERSTATE;

/*
 * Internal representation of the UDP Server handle.
 */
typedef struct RTUDPSERVER
{
    /** The magic value (RTUDPSERVER_MAGIC). */
    uint32_t volatile           u32Magic;
    /** The server state. */
    RTUDPSERVERSTATE volatile   enmState;
    /** The server thread. */
    RTTHREAD                    Thread;
    /** The server socket. */
    RTSOCKET volatile           hSocket;
    /** The datagram receiver function. */
    PFNRTUDPSERVE               pfnServe;
    /** Argument to pfnServer. */
    void                       *pvUser;
} RTUDPSERVER;


/*********************************************************************************************************************************
*   Internal Functions                                                                                                           *
*********************************************************************************************************************************/
static DECLCALLBACK(int)  rtUdpServerThread(RTTHREAD ThreadSelf, void *pvServer);
static int  rtUdpServerListen(PRTUDPSERVER pServer);
static int  rtUdpServerListenCleanup(PRTUDPSERVER pServer);
static int  rtUdpServerDestroySocket(RTSOCKET volatile *pSock, const char *pszMsg);
static int  rtUdpClose(RTSOCKET Sock, const char *pszMsg);


/**
 * Atomicly updates a socket variable.
 * @returns The old handle value.
 * @param   phSock          The socket handle variable to update.
 * @param   hNew            The new socket handle value.
 */
DECLINLINE(RTSOCKET) rtUdpAtomicXchgSock(RTSOCKET volatile *phSock, const RTSOCKET hNew)
{
    RTSOCKET hRet;
    ASMAtomicXchgHandle(phSock, hNew, &hRet);
    return hRet;
}


/**
 * Tries to change the UDP server state.
 */
DECLINLINE(bool) rtUdpServerTrySetState(PRTUDPSERVER pServer, RTUDPSERVERSTATE enmStateNew, RTUDPSERVERSTATE enmStateOld)
{
    bool fRc;
    ASMAtomicCmpXchgSize(&pServer->enmState, enmStateNew, enmStateOld, fRc);
    return fRc;
}

/**
 * Changes the UDP server state.
 */
DECLINLINE(void) rtUdpServerSetState(PRTUDPSERVER pServer, RTUDPSERVERSTATE enmStateNew, RTUDPSERVERSTATE enmStateOld)
{
    bool fRc;
    ASMAtomicCmpXchgSize(&pServer->enmState, enmStateNew, enmStateOld, fRc);
    Assert(fRc); NOREF(fRc);
}


/**
 * Closes a socket.
 *
 * @returns IPRT status code.
 */
static int rtUdpServerDestroySocket(RTSOCKET volatile *pSock, const char *pszMsg)
{
    RTSOCKET hSocket = rtUdpAtomicXchgSock(pSock, NIL_RTSOCKET);
    if (hSocket != NIL_RTSOCKET)
    {
        return rtUdpClose(hSocket, pszMsg);
    }
    return VINF_UDP_SERVER_NO_CLIENT;
}


RTR3DECL(int)  RTUdpServerCreate(const char *pszAddress, unsigned uPort, RTTHREADTYPE enmType, const char *pszThrdName,
                                 PFNRTUDPSERVE pfnServe, void *pvUser, PPRTUDPSERVER ppServer)
{
    /*
     * Validate input.
     */
    AssertReturn(uPort > 0, VERR_INVALID_PARAMETER);
    AssertPtrReturn(pfnServe, VERR_INVALID_POINTER);
    AssertPtrReturn(pszThrdName, VERR_INVALID_POINTER);
    AssertPtrReturn(ppServer, VERR_INVALID_POINTER);

    /*
     * Create the server.
     */
    PRTUDPSERVER pServer;
    int rc = RTUdpServerCreateEx(pszAddress, uPort, &pServer);
    if (RT_SUCCESS(rc))
    {
        /*
         * Create the listener thread.
         */
        RTMemPoolRetain(pServer);
        pServer->enmState   = RTUDPSERVERSTATE_STARTING;
        pServer->pvUser     = pvUser;
        pServer->pfnServe   = pfnServe;
        rc = RTThreadCreate(&pServer->Thread, rtUdpServerThread, pServer, 0, enmType, /*RTTHREADFLAGS_WAITABLE*/0, pszThrdName);
        if (RT_SUCCESS(rc))
        {
            /* done */
            if (ppServer)
                *ppServer = pServer;
            else
                RTMemPoolRelease(RTMEMPOOL_DEFAULT, pServer);
            return rc;
        }
        RTMemPoolRelease(RTMEMPOOL_DEFAULT, pServer);

        /*
         * Destroy the server.
         */
        rtUdpServerSetState(pServer, RTUDPSERVERSTATE_CREATED, RTUDPSERVERSTATE_STARTING);
        RTUdpServerDestroy(pServer);
    }

    return rc;
}


/**
 * Server thread, loops waiting for datagrams until it's terminated.
 *
 * @returns iprt status code. (ignored).
 * @param   ThreadSelf      Thread handle.
 * @param   pvServer        Server handle.
 */
static DECLCALLBACK(int)  rtUdpServerThread(RTTHREAD ThreadSelf, void *pvServer)
{
    PRTUDPSERVER    pServer = (PRTUDPSERVER)pvServer;
    int             rc;
    if (rtUdpServerTrySetState(pServer, RTUDPSERVERSTATE_WAITING, RTUDPSERVERSTATE_STARTING))
        rc = rtUdpServerListen(pServer);
    else
        rc = rtUdpServerListenCleanup(pServer);
    RTMemPoolRelease(RTMEMPOOL_DEFAULT, pServer);
    NOREF(ThreadSelf);
    return VINF_SUCCESS;
}


RTR3DECL(int) RTUdpServerCreateEx(const char *pszAddress, uint32_t uPort, PPRTUDPSERVER ppServer)
{

    /*
     * Validate input.
     */
    AssertReturn(uPort > 0, VERR_INVALID_PARAMETER);
    AssertPtrReturn(ppServer, VERR_INVALID_PARAMETER);

    /*
     * Resolve the address.
     */
    RTNETADDR LocalAddr;
    int rc = RTSocketParseInetAddress(pszAddress, uPort, &LocalAddr);
    if (RT_FAILURE(rc))
        return rc;

    /*
     * Setting up socket.
     */
    RTSOCKET Sock;
    rc = rtSocketCreate(&Sock, AF_INET, SOCK_DGRAM, IPPROTO_UDP, false /*fInheritable*/);
    if (RT_SUCCESS(rc))
    {
        /*
         * Set socket options.
         */
        int fFlag = 1;
        if (!rtSocketSetOpt(Sock, SOL_SOCKET, SO_REUSEADDR, &fFlag, sizeof(fFlag)))
        {
            /*
             * Bind a name to the socket.
             */
            rc = rtSocketBind(Sock, &LocalAddr);
            if (RT_SUCCESS(rc))
            {
                /*
                 * Create the server handle.
                 */
                PRTUDPSERVER pServer = (PRTUDPSERVER)RTMemPoolAlloc(RTMEMPOOL_DEFAULT, sizeof(*pServer));
                if (pServer)
                {
                    pServer->u32Magic   = RTUDPSERVER_MAGIC;
                    pServer->enmState   = RTUDPSERVERSTATE_CREATED;
                    pServer->Thread     = NIL_RTTHREAD;
                    pServer->hSocket    = Sock;
                    pServer->pfnServe   = NULL;
                    pServer->pvUser     = NULL;
                    *ppServer = pServer;
                    return VINF_SUCCESS;
                }

                /* bail out */
                rc = VERR_NO_MEMORY;
            }
        }
        else
            AssertMsgFailed(("rtSocketSetOpt: %Rrc\n", rc));
        rtUdpClose(Sock, "RTServerCreateEx");
    }

    return rc;
}


RTR3DECL(int) RTUdpServerListen(PRTUDPSERVER pServer, PFNRTUDPSERVE pfnServe, void *pvUser)
{
    /*
     * Validate input and retain the instance.
     */
    AssertPtrReturn(pfnServe, VERR_INVALID_POINTER);
    AssertPtrReturn(pServer, VERR_INVALID_HANDLE);
    AssertReturn(pServer->u32Magic == RTUDPSERVER_MAGIC, VERR_INVALID_HANDLE);
    AssertReturn(RTMemPoolRetain(pServer) != UINT32_MAX, VERR_INVALID_HANDLE);

    int rc = VERR_INVALID_STATE;
    if (rtUdpServerTrySetState(pServer, RTUDPSERVERSTATE_WAITING, RTUDPSERVERSTATE_CREATED))
    {
        Assert(!pServer->pfnServe);
        Assert(!pServer->pvUser);
        Assert(pServer->Thread == NIL_RTTHREAD);

        pServer->pfnServe = pfnServe;
        pServer->pvUser   = pvUser;
        pServer->Thread   = RTThreadSelf();
        Assert(pServer->Thread != NIL_RTTHREAD);
        rc = rtUdpServerListen(pServer);
    }
    else
    {
        AssertMsgFailed(("enmState=%d\n", pServer->enmState));
        rc = VERR_INVALID_STATE;
    }
    RTMemPoolRelease(RTMEMPOOL_DEFAULT, pServer);
    return rc;
}


/**
 * Internal worker common for RTUdpServerListen and the thread created by
 * RTUdpServerCreate().
 *
 * The caller makes sure it has its own memory reference and releases it upon
 * return.
 */
static int rtUdpServerListen(PRTUDPSERVER pServer)
{
    /*
     * Wait for incoming datagrams loop.
     */
    for (;;)
    {
        /*
         * Change state, getting an extra reference to the socket so we can
         * allow others to close it while we're stuck in rtSocketAccept.
         */
        RTUDPSERVERSTATE    enmState      = pServer->enmState;
        RTSOCKET            hSocket;
        ASMAtomicReadHandle(&pServer->hSocket, &hSocket);
        if (hSocket != NIL_RTSOCKET)
            RTSocketRetain(hSocket);
        if (    enmState != RTUDPSERVERSTATE_WAITING
            &&  enmState != RTUDPSERVERSTATE_RECEIVING)
        {
            RTSocketRelease(hSocket);
            return rtUdpServerListenCleanup(pServer);
        }
        if (!rtUdpServerTrySetState(pServer, RTUDPSERVERSTATE_WAITING, enmState))
        {
            RTSocketRelease(hSocket);
            continue;
        }

        /*
         * Wait for incoming datagrams or errors.
         */
        uint32_t fEvents;
        int rc = RTSocketSelectOneEx(hSocket, RTSOCKET_EVT_READ | RTSOCKET_EVT_ERROR, &fEvents, 1000);
        RTSocketRelease(hSocket);
        if (rc == VERR_TIMEOUT)
            continue;
        if (RT_FAILURE(rc))
        {
            /* These are typical for what can happen during destruction. */
            if (   rc == VERR_INVALID_HANDLE
                || rc == VERR_INVALID_PARAMETER
                || rc == VERR_NET_NOT_SOCKET)
                return rtUdpServerListenCleanup(pServer);
            continue;
        }
        if (fEvents & RTSOCKET_EVT_ERROR)
            return rtUdpServerListenCleanup(pServer);

        /*
         * Run a pfnServe callback.
         */
        if (!rtUdpServerTrySetState(pServer, RTUDPSERVERSTATE_RECEIVING, RTUDPSERVERSTATE_WAITING))
            return rtUdpServerListenCleanup(pServer);
        rc = pServer->pfnServe(hSocket, pServer->pvUser);

        /*
         * Stop the server?
         */
        if (rc == VERR_UDP_SERVER_STOP)
        {
            if (rtUdpServerTrySetState(pServer, RTUDPSERVERSTATE_STOPPING, RTUDPSERVERSTATE_RECEIVING))
            {
                /*
                 * Reset the server socket and change the state to stopped. After that state change
                 * we cannot safely access the handle so we'll have to return here.
                 */
                hSocket = rtUdpAtomicXchgSock(&pServer->hSocket, NIL_RTSOCKET);
                rtUdpServerSetState(pServer, RTUDPSERVERSTATE_STOPPED, RTUDPSERVERSTATE_STOPPING);
                rtUdpClose(hSocket, "Listener: server stopped");
            }
            else
                rtUdpServerListenCleanup(pServer); /* ignore rc */
            return rc;
        }
    }
}


/**
 * Clean up after listener.
 */
static int rtUdpServerListenCleanup(PRTUDPSERVER pServer)
{
    /*
     * Close the server socket.
     */
    rtUdpServerDestroySocket(&pServer->hSocket, "ListenCleanup");

    /*
     * Figure the return code and make sure the state is OK.
     */
    RTUDPSERVERSTATE enmState = pServer->enmState;
    switch (enmState)
    {
        case RTUDPSERVERSTATE_STOPPING:
        case RTUDPSERVERSTATE_STOPPED:
            return VERR_UDP_SERVER_SHUTDOWN;

        case RTUDPSERVERSTATE_WAITING:
            rtUdpServerTrySetState(pServer, RTUDPSERVERSTATE_STOPPED, enmState);
            return VERR_UDP_SERVER_DESTROYED;

        case RTUDPSERVERSTATE_DESTROYING:
            return VERR_UDP_SERVER_DESTROYED;

        case RTUDPSERVERSTATE_STARTING:
        case RTUDPSERVERSTATE_RECEIVING:
        default:
            AssertMsgFailedReturn(("pServer=%p enmState=%d\n", pServer, enmState), VERR_INTERNAL_ERROR_4);
    }
}


RTR3DECL(int) RTUdpServerShutdown(PRTUDPSERVER pServer)
{
    /*
     * Validate input and retain the instance.
     */
    AssertPtrReturn(pServer, VERR_INVALID_HANDLE);
    AssertReturn(pServer->u32Magic == RTUDPSERVER_MAGIC, VERR_INVALID_HANDLE);
    AssertReturn(RTMemPoolRetain(pServer) != UINT32_MAX, VERR_INVALID_HANDLE);

    /*
     * Try change the state to stopping, then replace and destroy the server socket.
     */
    for (;;)
    {
        RTUDPSERVERSTATE enmState = pServer->enmState;
        if (    enmState != RTUDPSERVERSTATE_WAITING
            &&  enmState != RTUDPSERVERSTATE_RECEIVING)
        {
            RTMemPoolRelease(RTMEMPOOL_DEFAULT, pServer);
            switch (enmState)
            {
                case RTUDPSERVERSTATE_CREATED:
                case RTUDPSERVERSTATE_STARTING:
                default:
                    AssertMsgFailed(("%d\n", enmState));
                    return VERR_INVALID_STATE;

                case RTUDPSERVERSTATE_STOPPING:
                case RTUDPSERVERSTATE_STOPPED:
                    return VINF_SUCCESS;

                case RTUDPSERVERSTATE_DESTROYING:
                    return VERR_UDP_SERVER_DESTROYED;
            }
        }
        if (rtUdpServerTrySetState(pServer, RTUDPSERVERSTATE_STOPPING, enmState))
        {
            rtUdpServerDestroySocket(&pServer->hSocket, "RTUdpServerShutdown");
            rtUdpServerSetState(pServer, RTUDPSERVERSTATE_STOPPED, RTUDPSERVERSTATE_STOPPING);

            RTMemPoolRelease(RTMEMPOOL_DEFAULT, pServer);
            return VINF_SUCCESS;
        }
    }
}


RTR3DECL(int) RTUdpServerDestroy(PRTUDPSERVER pServer)
{
    /*
     * Validate input and retain the instance.
     */
    AssertPtrReturn(pServer, VERR_INVALID_HANDLE);
    AssertReturn(pServer->u32Magic == RTUDPSERVER_MAGIC, VERR_INVALID_HANDLE);
    AssertReturn(RTMemPoolRetain(pServer) != UINT32_MAX, VERR_INVALID_HANDLE); /* paranoia */

    /*
     * Move the state along so the listener can figure out what's going on.
     */
    for (;;)
    {
        bool             fDestroyable;
        RTUDPSERVERSTATE enmState = pServer->enmState;
        switch (enmState)
        {
            case RTUDPSERVERSTATE_STARTING:
            case RTUDPSERVERSTATE_WAITING:
            case RTUDPSERVERSTATE_RECEIVING:
            case RTUDPSERVERSTATE_CREATED:
            case RTUDPSERVERSTATE_STOPPED:
                fDestroyable = rtUdpServerTrySetState(pServer, RTUDPSERVERSTATE_DESTROYING, enmState);
                break;

            /* destroyable states */
            case RTUDPSERVERSTATE_STOPPING:
                fDestroyable = true;
                break;

            /*
             * Everything else means user or internal misbehavior.
             */
            default:
                AssertMsgFailed(("pServer=%p enmState=%d\n", pServer, enmState));
                RTMemPoolRelease(RTMEMPOOL_DEFAULT, pServer);
                return VERR_INTERNAL_ERROR;
        }
        if (fDestroyable)
            break;
    }

    /*
     * Destroy it.
     */
    ASMAtomicWriteU32(&pServer->u32Magic, ~RTUDPSERVER_MAGIC);
    rtUdpServerDestroySocket(&pServer->hSocket, "Destroyer: server");

    /*
     * Release it.
     */
    RTMemPoolRelease(RTMEMPOOL_DEFAULT, pServer);
    RTMemPoolRelease(RTMEMPOOL_DEFAULT, pServer);
    return VINF_SUCCESS;
}


/**
 * Internal close function which does all the proper bitching.
 */
static int rtUdpClose(RTSOCKET Sock, const char *pszMsg)
{
    NOREF(pszMsg); /** @todo drop this parameter? */

    /* ignore nil handles. */
    if (Sock == NIL_RTSOCKET)
        return VINF_SUCCESS;

    /*
     * Close the socket handle (drops our reference to it).
     */
    return RTSocketClose(Sock);
}


RTR3DECL(int) RTUdpRead(RTSOCKET Sock, void *pvBuffer, size_t cbBuffer, size_t *pcbRead, PRTNETADDR pSrcAddr)
{
    if (!RT_VALID_PTR(pcbRead))
        return VERR_INVALID_POINTER;
    return RTSocketReadFrom(Sock, pvBuffer, cbBuffer, pcbRead, pSrcAddr);
}


RTR3DECL(int)  RTUdpWrite(PRTUDPSERVER pServer, const void *pvBuffer, size_t cbBuffer, PCRTNETADDR pDstAddr)
{
    /*
     * Validate input and retain the instance.
     */
    AssertPtrReturn(pServer, VERR_INVALID_HANDLE);
    AssertReturn(pServer->u32Magic == RTUDPSERVER_MAGIC, VERR_INVALID_HANDLE);
    AssertReturn(RTMemPoolRetain(pServer) != UINT32_MAX, VERR_INVALID_HANDLE);

    RTSOCKET hSocket;
    ASMAtomicReadHandle(&pServer->hSocket, &hSocket);
    if (hSocket == NIL_RTSOCKET)
    {
        RTMemPoolRelease(RTMEMPOOL_DEFAULT, pServer);
        return VERR_INVALID_HANDLE;
    }
    RTSocketRetain(hSocket);

    int rc = VINF_SUCCESS;
    RTUDPSERVERSTATE enmState = pServer->enmState;
    if (    enmState != RTUDPSERVERSTATE_CREATED
        &&  enmState != RTUDPSERVERSTATE_STARTING
        &&  enmState != RTUDPSERVERSTATE_WAITING
        &&  enmState != RTUDPSERVERSTATE_RECEIVING
        &&  enmState != RTUDPSERVERSTATE_STOPPING)
        rc = VERR_INVALID_STATE;

    if (RT_SUCCESS(rc))
        rc = RTSocketWriteTo(hSocket, pvBuffer, cbBuffer, pDstAddr);

    RTSocketRelease(hSocket);
    RTMemPoolRelease(RTMEMPOOL_DEFAULT, pServer);

    return rc;
}


RTR3DECL(int) RTUdpCreateClientSocket(const char *pszAddress, uint32_t uPort, PRTNETADDR pLocalAddr, PRTSOCKET pSock)
{
    /*
     * Validate input.
     */
    AssertReturn(uPort > 0, VERR_INVALID_PARAMETER);
    AssertPtrReturn(pszAddress, VERR_INVALID_POINTER);
    AssertPtrReturn(pSock, VERR_INVALID_POINTER);

    /*
     * Resolve the address.
     */
    RTNETADDR Addr;
    int rc = RTSocketParseInetAddress(pszAddress, uPort, &Addr);
    if (RT_FAILURE(rc))
        return rc;

    /*
     * Create the socket and connect.
     */
    RTSOCKET Sock;
    rc = rtSocketCreate(&Sock, AF_INET, SOCK_DGRAM, 0, false /*fInheritable*/);
    if (RT_SUCCESS(rc))
    {
        if (pLocalAddr)
            rc = rtSocketBind(Sock, pLocalAddr);
        if (RT_SUCCESS(rc))
        {
            rc = rtSocketConnect(Sock, &Addr, RT_SOCKETCONNECT_DEFAULT_WAIT);
            if (RT_SUCCESS(rc))
            {
                *pSock = Sock;
                return VINF_SUCCESS;
            }
        }
        RTSocketClose(Sock);
    }
    return rc;
}


RTR3DECL(int) RTUdpCreateServerSocket(const char *pszAddress, uint32_t uPort, PRTSOCKET pSock)
{
    /*
     * Validate input.
     */
    AssertReturn(uPort > 0, VERR_INVALID_PARAMETER);
    AssertPtrReturn(pszAddress, VERR_INVALID_POINTER);
    AssertPtrReturn(pSock, VERR_INVALID_POINTER);

    /*
     * Resolve the address.
     */
    RTNETADDR LocalAddr;
    int rc = RTSocketParseInetAddress(pszAddress, uPort, &LocalAddr);
    if (RT_FAILURE(rc))
        return rc;

    /*
     * Setting up socket.
     */
    RTSOCKET Sock;
    rc = rtSocketCreate(&Sock, AF_INET, SOCK_DGRAM, IPPROTO_UDP, false /*fInheritable*/);
    if (RT_SUCCESS(rc))
    {
        /*
         * Set socket options.
         */
        int fFlag = 1;
        if (!rtSocketSetOpt(Sock, SOL_SOCKET, SO_REUSEADDR, &fFlag, sizeof(fFlag)))
        {
            /*
             * Bind a name to the socket.
             */
            rc = rtSocketBind(Sock, &LocalAddr);
            if (RT_SUCCESS(rc))
            {
                *pSock = Sock;
                return VINF_SUCCESS;
            }
        }
        RTSocketClose(Sock);
    }
    return rc;
}