summaryrefslogtreecommitdiff
path: root/src/VBox/Runtime/r3/tcp.cpp
blob: af3d23af1023256f347de47cb053d756d25dff39 (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
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
/* $Id: tcp.cpp $ */
/** @file
 * IPRT - TCP/IP.
 */

/*
 * Copyright (C) 2006-2007 Sun Microsystems, Inc.
 *
 * This file is part of VirtualBox Open Source Edition (OSE), as
 * available from http://www.virtualbox.org. This file is free software;
 * you can redistribute it and/or modify it under the terms of the GNU
 * General Public License (GPL) as published by the Free Software
 * Foundation, in version 2 as it comes in the "COPYING" file of the
 * VirtualBox OSE distribution. VirtualBox OSE is distributed in the
 * hope that it will be useful, but WITHOUT ANY WARRANTY of any kind.
 *
 * The contents of this file may alternatively be used under the terms
 * of the Common Development and Distribution License Version 1.0
 * (CDDL) only, as it comes in the "COPYING.CDDL" file of the
 * VirtualBox OSE 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.
 *
 * Please contact Sun Microsystems, Inc., 4150 Network Circle, Santa
 * Clara, CA 95054 USA or visit http://www.sun.com if you need
 * additional information or have any questions.
 */


/*******************************************************************************
*   Header Files                                                               *
*******************************************************************************/
#ifdef RT_OS_WINDOWS
#include <winsock.h>
#else /* !RT_OS_WINDOWS */
#include <errno.h>
#include <sys/stat.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <netinet/tcp.h>
#include <arpa/inet.h>
#include <sys/un.h>
#include <netdb.h>
#include <unistd.h>
#endif /* !RT_OS_WINDOWS */

#include <iprt/tcp.h>
#include <iprt/thread.h>
#include <iprt/alloc.h>
#include <iprt/assert.h>
#include <iprt/asm.h>
#include <iprt/err.h>
#include <iprt/string.h>


/* non-standard linux stuff (it seems). */
#ifndef MSG_NOSIGNAL
# define MSG_NOSIGNAL 0
#endif
#ifndef SHUT_RDWR
# ifdef SD_BOTH
#  define SHUT_RDWR SD_BOTH
# else
#  define SHUT_RDWR 2
# endif
#endif

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


/*******************************************************************************
*   Defined Constants And Macros                                               *
*******************************************************************************/
#define BACKLOG         10   /* how many pending connections queue will hold */


/*******************************************************************************
*   Structures and Typedefs                                                    *
*******************************************************************************/
/**
 * TCP Server state.
 */
typedef enum RTTCPSERVERSTATE
{
    /** Invalid. */
    RTTCPSERVERSTATE_INVALID = 0,
    /** Created. */
    RTTCPSERVERSTATE_CREATED,
    /** Listener thread is starting up. */
    RTTCPSERVERSTATE_STARTING,
    /** Accepting client connections. */
    RTTCPSERVERSTATE_ACCEPTING,
    /** Serving a client. */
    RTTCPSERVERSTATE_SERVING,
    /** Listener terminating. */
    RTTCPSERVERSTATE_STOPPING,
    /** Listener terminated. */
    RTTCPSERVERSTATE_STOPPED,
    /** Destroying signaling to the listener, listener will wait. */
    RTTCPSERVERSTATE_SIGNALING,
    /** Listener cleans up. */
    RTTCPSERVERSTATE_DESTROYING,
    /** Freed. */
    RTTCPSERVERSTATE_FREED
} RTTCPSERVERSTATE;

/*
 * Internal representation of the TCP Server handle.
 */
typedef struct RTTCPSERVER
{
    /** The server state. */
    RTTCPSERVERSTATE volatile   enmState;
    /** The server thread. */
    RTTHREAD                    Thread;
    /** The server socket. */
    RTSOCKET volatile           SockServer;
    /** The socket to the client currently being serviced.
     * This is NIL_RTSOCKET when no client is serviced. */
    RTSOCKET volatile           SockClient;
    /** The connection function. */
    PFNRTTCPSERVE               pfnServe;
    /** Argument to pfnServer. */
    void                       *pvUser;
} RTTCPSERVER;


/*******************************************************************************
*   Internal Functions                                                         *
*******************************************************************************/
static DECLCALLBACK(int)  rtTcpServerThread(RTTHREAD ThreadSelf, void *pvServer);
static int rtTcpServerListen(PRTTCPSERVER pServer);
static void rcTcpServerListenCleanup(PRTTCPSERVER pServer);
static void rtTcpServerDestroyServerSock(RTSOCKET SockServer, const char *pszMsg);
static int rtTcpClose(RTSOCKET Sock, const char *pszMsg);



/**
 * Get the last error as an iprt status code.
 *
 * @returns iprt status code.
 */
DECLINLINE(int) rtTcpError(void)
{
#ifdef RT_OS_WINDOWS
    return RTErrConvertFromWin32(WSAGetLastError());
#else
    return RTErrConvertFromErrno(errno);
#endif
}


/**
 * Resets the last error.
 */
DECLINLINE(void) rtTcpErrorReset(void)
{
#ifdef RT_OS_WINDOWS
    WSASetLastError(0);
#else
    errno = 0;
#endif
}


/**
 * Get the last resolver error as an iprt status code.
 *
 * @returns iprt status code.
 */
DECLINLINE(int) rtTcpResolverError(void)
{
#ifdef RT_OS_WINDOWS
    return RTErrConvertFromWin32(WSAGetLastError());
#else
    switch (h_errno)
    {
        case HOST_NOT_FOUND:
            return VERR_NET_HOST_NOT_FOUND;
        case NO_DATA:
            return VERR_NET_ADDRESS_NOT_AVAILABLE;
        case NO_RECOVERY:
            return VERR_IO_GEN_FAILURE;
        case TRY_AGAIN:
            return VERR_TRY_AGAIN;

        default:
            return VERR_UNRESOLVED_ERROR;
    }
#endif
}


/**
 * Atomicly updates a socket variable.
 * @returns The old value.
 * @param   pSock   The socket variable to update.
 * @param   Sock    The new value.
 */
DECLINLINE(RTSOCKET) rtTcpAtomicXchgSock(RTSOCKET volatile *pSock, const RTSOCKET Sock)
{
    switch (sizeof(RTSOCKET))
    {
        case 4: return (RTSOCKET)ASMAtomicXchgS32((int32_t volatile *)pSock, (int32_t)Sock);
        default:
            AssertReleaseFailed();
            return NIL_RTSOCKET;
    }
}


/**
 * Changes the TCP server state.
 */
DECLINLINE(bool) rtTcpServerSetState(PRTTCPSERVER pServer, RTTCPSERVERSTATE enmStateNew, RTTCPSERVERSTATE enmStateOld)
{
    bool fRc;
    ASMAtomicCmpXchgSize(&pServer->enmState, enmStateNew, enmStateOld, fRc);
    return fRc;
}


/**
 * Create single connection at a time TCP Server in a separate thread.
 *
 * The thread will loop accepting connections and call pfnServe for
 * each of the incoming connections in turn. The pfnServe function can
 * return VERR_TCP_SERVER_STOP too terminate this loop. RTTcpServerDestroy()
 * should be used to terminate the server.
 *
 * @returns iprt status code.
 * @param   pszAddress      The address for creating a listening socket.
 *                          If NULL or empty string the server is bound to all interfaces.
 * @param   uPort           The port for creating a listening socket.
 * @param   enmType         The thread type.
 * @param   pszThrdName     The name of the worker thread.
 * @param   pfnServe        The function which will serve a new client connection.
 * @param   pvUser          User argument passed to pfnServe.
 * @param   ppServer        Where to store the serverhandle.
 */
RTR3DECL(int)  RTTcpServerCreate(const char *pszAddress, unsigned uPort, RTTHREADTYPE enmType, const char *pszThrdName,
                                 PFNRTTCPSERVE pfnServe, void *pvUser, PPRTTCPSERVER ppServer)
{
    /*
     * Do params checking
     */
    if (!uPort || !pfnServe || !pszThrdName || !ppServer)
    {
        AssertMsgFailed(("Invalid params\n"));
        return VERR_INVALID_PARAMETER;
    }

    /*
     * Create the server.
     */
    PRTTCPSERVER    pServer;
    int rc = RTTcpServerCreateEx(pszAddress, uPort, &pServer);
    if (RT_SUCCESS(rc))
    {
        /*
         * Create the listener thread.
         */
        pServer->enmState   = RTTCPSERVERSTATE_STARTING;
        pServer->pvUser     = pvUser;
        pServer->pfnServe   = pfnServe;
        rc = RTThreadCreate(&pServer->Thread, rtTcpServerThread, pServer, 0, enmType, /*RTTHREADFLAGS_WAITABLE*/0, pszThrdName);
        if (RT_SUCCESS(rc))
        {
            /* done */
            if (ppServer)
                *ppServer = pServer;
            return rc;
        }

        /*
         * Destroy the server.
         */
        rtTcpServerSetState(pServer, RTTCPSERVERSTATE_CREATED, RTTCPSERVERSTATE_STARTING);
        RTTcpServerDestroy(pServer);
    }

    return rc;
}


/**
 * Server thread, loops accepting connections until it's terminated.
 *
 * @returns iprt status code. (ignored).
 * @param   ThreadSelf      Thread handle.
 * @param   pvServer        Server handle.
 */
static DECLCALLBACK(int)  rtTcpServerThread(RTTHREAD ThreadSelf, void *pvServer)
{
    PRTTCPSERVER    pServer = (PRTTCPSERVER)pvServer;
    if (rtTcpServerSetState(pServer, RTTCPSERVERSTATE_ACCEPTING, RTTCPSERVERSTATE_STARTING))
        return rtTcpServerListen(pServer);
    rcTcpServerListenCleanup(pServer);
    NOREF(ThreadSelf);
    return VINF_SUCCESS;
}


/**
 * Create single connection at a time TCP Server.
 * The caller must call RTTcpServerListen() to actually start the server.
 *
 * @returns iprt status code.
 * @param   pszAddress      The address for creating a listening socket.
 *                          If NULL the server is bound to all interfaces.
 * @param   uPort           The port for creating a listening socket.
 * @param   ppServer        Where to store the serverhandle.
 */
RTR3DECL(int) RTTcpServerCreateEx(const char *pszAddress, uint32_t uPort, PPRTTCPSERVER ppServer)
{
    int rc;

    /*
     * Do params checking
     */
    if (!uPort || !ppServer)
    {
        AssertMsgFailed(("Invalid params\n"));
        return VERR_INVALID_PARAMETER;
    }

#ifdef RT_OS_WINDOWS
    /*
     * Initialize WinSock and check version.
     */
    WORD    wVersionRequested = MAKEWORD(1, 1);
    WSADATA wsaData;
    rc = WSAStartup(wVersionRequested, &wsaData);
    if (wsaData.wVersion != wVersionRequested)
    {
        AssertMsgFailed(("Wrong winsock version\n"));
        return VERR_NOT_SUPPORTED;
    }
#endif

    /*
     * Get host listening address.
     */
    struct hostent *pHostEnt = NULL;
    if (pszAddress != NULL && *pszAddress)
    {
        pHostEnt = gethostbyname(pszAddress);
        if (!pHostEnt)
        {
            struct in_addr InAddr;
            InAddr.s_addr = inet_addr(pszAddress);
            pHostEnt = gethostbyaddr((char *)&InAddr, 4, AF_INET);
            if (!pHostEnt)
            {
                rc = rtTcpResolverError();
                AssertMsgFailed(("Could not get host address rc=%Rrc\n", rc));
                return rc;
            }
        }
    }

    /*
     * Setting up socket.
     */
    RTSOCKET WaitSock = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP);
    if (WaitSock != -1)
    {
        /*
         * Set socket options.
         */
        int fFlag = 1;
        if (!setsockopt(WaitSock, SOL_SOCKET, SO_REUSEADDR, (const char *)&fFlag, sizeof(fFlag)))
        {
            /*
             * Set socket family, address and port.
             */
            struct sockaddr_in LocalAddr = {0};
            LocalAddr.sin_family = AF_INET;
            LocalAddr.sin_port = htons(uPort);
            /* if address not specified, use INADDR_ANY. */
            if (!pHostEnt)
                LocalAddr.sin_addr.s_addr = INADDR_ANY;
            else
                LocalAddr.sin_addr = *((struct in_addr *)pHostEnt->h_addr);

            /*
             * Bind a name to a socket.
             */
            if (bind(WaitSock, (struct sockaddr *)&LocalAddr, sizeof(LocalAddr)) != -1)
            {
                /*
                 * Listen for connections on a socket.
                 */
                if (listen(WaitSock, BACKLOG) != -1)
                {
                    /*
                     * Create the server handle.
                     */
                    PRTTCPSERVER    pServer = (PRTTCPSERVER)RTMemAllocZ(sizeof(*pServer));
                    if (pServer)
                    {
                        pServer->SockServer = WaitSock;
                        pServer->SockClient = NIL_RTSOCKET;
                        pServer->Thread     = NIL_RTTHREAD;
                        pServer->enmState   = RTTCPSERVERSTATE_CREATED;
                        *ppServer = pServer;
                        return VINF_SUCCESS;
                    }
                    else
                        rc = VERR_NO_MEMORY;
                }
                else
                {
                    rc = rtTcpError();
                    AssertMsgFailed(("listen() %Rrc\n", rc));
                }
            }
            else
            {
                rc = rtTcpError();
            }
        }
        else
        {
            rc = rtTcpError();
            AssertMsgFailed(("setsockopt() %Rrc\n", rc));
        }
        rtTcpClose(WaitSock, "RTServerCreateEx");
    }
    else
    {
        rc = rtTcpError();
        AssertMsgFailed(("socket() %Rrc\n", rc));
    }

    return rc;
}


/**
 * Listen for incoming connections.
 *
 * The function will loop accepting connections and call pfnServe for
 * each of the incoming connections in turn. The pfnServe function can
 * return VERR_TCP_SERVER_STOP too terminate this loop. A stopped server
 * can only be destroyed.
 *
 * @returns iprt status code.
 * @param   pServer         The server handle as returned from RTTcpServerCreateEx().
 * @param   pfnServe        The function which will serve a new client connection.
 * @param   pvUser          User argument passed to pfnServe.
 */
RTR3DECL(int) RTTcpServerListen(PRTTCPSERVER pServer, PFNRTTCPSERVE pfnServe, void *pvUser)
{
    /*
     * Validate input.
     */
    if (!pfnServe || !pServer)
    {
        AssertMsgFailed(("pfnServer=%p pServer=%p\n", pfnServe, pServer));
        return VERR_INVALID_PARAMETER;
    }
    if (rtTcpServerSetState(pServer, RTTCPSERVERSTATE_ACCEPTING, RTTCPSERVERSTATE_CREATED))
    {
        Assert(!pServer->pfnServe);
        Assert(!pServer->pvUser);
        Assert(pServer->Thread == NIL_RTTHREAD);
        Assert(pServer->SockClient == NIL_RTSOCKET);

        pServer->pfnServe = pfnServe;
        pServer->pvUser   = pvUser;
        pServer->Thread   = RTThreadSelf();
        Assert(pServer->Thread != NIL_RTTHREAD);
        return rtTcpServerListen(pServer);
    }
    AssertMsgFailed(("pServer->enmState=%d\n", pServer->enmState));
    return VERR_INVALID_PARAMETER;
}


/**
 * Closes the client socket.
 */
static int rtTcpServerDestroyClientSock(RTSOCKET volatile *pSock, const char *pszMsg)
{
    RTSOCKET Sock = rtTcpAtomicXchgSock(pSock, NIL_RTSOCKET);
    if (Sock != NIL_RTSOCKET)
        shutdown(Sock, SHUT_RDWR);
    return rtTcpClose(Sock, pszMsg);
}


/**
 * Internal worker common for RTTcpServerListen and the thread created by RTTcpServerCreate().
 */
static int rtTcpServerListen(PRTTCPSERVER pServer)
{
    /*
     * Accept connection loop.
     */
    int rc = VINF_SUCCESS;
    for (;;)
    {
        /*
         * Change state.
         */
        RTTCPSERVERSTATE enmState = pServer->enmState;
        if (    enmState != RTTCPSERVERSTATE_ACCEPTING
            &&  enmState != RTTCPSERVERSTATE_SERVING)
            break;
        if (!rtTcpServerSetState(pServer, RTTCPSERVERSTATE_ACCEPTING, enmState))
            continue;

        /*
         * Accept connection.
         */
        struct sockaddr_in RemoteAddr = {0};
        socklen_t Len = sizeof(RemoteAddr);
        RTSOCKET Socket = accept(pServer->SockServer, (struct sockaddr *)&RemoteAddr, &Len);
        if (Socket == -1)
        {
#ifndef RT_OS_WINDOWS
            /* These are typical for what can happen during destruction. */
            if (errno == EBADF || errno == EINVAL || errno == ENOTSOCK)
                break;
#endif
            continue;
        }

        /*
         * Run a pfnServe callback.
         */
        if (!rtTcpServerSetState(pServer, RTTCPSERVERSTATE_SERVING, RTTCPSERVERSTATE_ACCEPTING))
            break;
        rtTcpAtomicXchgSock(&pServer->SockClient, Socket);
        rc = pServer->pfnServe(Socket, pServer->pvUser);
        rtTcpServerDestroyClientSock(&pServer->SockClient, "Listener: client");

        /*
         * Stop the server?
         */
        if (rc == VERR_TCP_SERVER_STOP)
        {
            if (rtTcpServerSetState(pServer, RTTCPSERVERSTATE_STOPPING, RTTCPSERVERSTATE_SERVING))
            {
                /*
                 * 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.
                 */
                RTSOCKET SockServer = rtTcpAtomicXchgSock(&pServer->SockServer, NIL_RTSOCKET);
                rtTcpServerSetState(pServer, RTTCPSERVERSTATE_STOPPED, RTTCPSERVERSTATE_STOPPING);
                rtTcpClose(SockServer, "Listener: server stopped");
                return rc;
            }
            break;
        }
    }

    /*
     * Perform any pending clean and be gone.
     */
    rcTcpServerListenCleanup(pServer);
    return rc;
}


/**
 * Clean up after listener.
 */
static void rcTcpServerListenCleanup(PRTTCPSERVER pServer)
{
    /*
     * Wait for any destroyers to finish signaling us.
     */
    for (unsigned cTries = 99; cTries > 0; cTries--)
    {
        RTTCPSERVERSTATE enmState = pServer->enmState;
        switch (enmState)
        {
            /*
             * Intermediate state while the destroyer closes the client socket.
             */
            case RTTCPSERVERSTATE_SIGNALING:
                if (!RTThreadYield())
                    RTThreadSleep(1);
                break;

            /*
             * Free the handle.
             */
            case RTTCPSERVERSTATE_DESTROYING:
            {
                rtTcpClose(rtTcpAtomicXchgSock(&pServer->SockServer, NIL_RTSOCKET), "Listener-cleanup: server");
                rtTcpServerSetState(pServer, RTTCPSERVERSTATE_FREED, RTTCPSERVERSTATE_DESTROYING);
                RTMemFree(pServer);
                return;
            }

            /*
             * Everything else means failure.
             */
            default:
                AssertMsgFailed(("pServer=%p enmState=%d\n", pServer, enmState));
                return;
        }
    }
    AssertMsgFailed(("Timed out when trying to clean up after listener. pServer=%p enmState=%d\n", pServer, pServer->enmState));
}


/**
 * Terminate the open connection to the server.
 *
 * @returns iprt status code.
 * @param   pServer         Handle to the server.
 */
RTR3DECL(int) RTTcpServerDisconnectClient(PRTTCPSERVER pServer)
{
    /*
     * Validate input.
     */
    if (    !pServer
        ||  pServer->enmState <= RTTCPSERVERSTATE_INVALID
        ||  pServer->enmState >= RTTCPSERVERSTATE_FREED)
    {
        AssertMsgFailed(("Invalid parameter!\n"));
        return VERR_INVALID_PARAMETER;
    }

    return rtTcpServerDestroyClientSock(&pServer->SockClient, "DisconnectClient: client");
}


/**
 * Closes down and frees a TCP Server.
 * This will also terminate any open connections to the server.
 *
 * @returns iprt status code.
 * @param   pServer         Handle to the server.
 */
RTR3DECL(int) RTTcpServerDestroy(PRTTCPSERVER pServer)
{
    /*
     * Validate input.
     */
    if (    !pServer
        ||  pServer->enmState <= RTTCPSERVERSTATE_INVALID
        ||  pServer->enmState >= RTTCPSERVERSTATE_FREED)
    {
        AssertMsgFailed(("Invalid parameter!\n"));
        return VERR_INVALID_PARAMETER;
    }

/** @todo r=bird: Some of this horrible code can probably be exchanged with a RTThreadWait(). (It didn't exist when this code was written.) */

    /*
     * Move it to the destroying state.
     */
    RTSOCKET    SockServer = rtTcpAtomicXchgSock(&pServer->SockServer, NIL_RTSOCKET);
    for (unsigned cTries = 99; cTries > 0; cTries--)
    {
        RTTCPSERVERSTATE enmState = pServer->enmState;
        switch (enmState)
        {
            /*
             * Try move it to the destroying state.
             */
            case RTTCPSERVERSTATE_STARTING:
            case RTTCPSERVERSTATE_ACCEPTING:
            case RTTCPSERVERSTATE_SERVING:
            {
                if (rtTcpServerSetState(pServer, RTTCPSERVERSTATE_SIGNALING, enmState))
                {
                    /* client */
                    rtTcpServerDestroyClientSock(&pServer->SockClient, "Destroyer: client");

                    bool fRc = rtTcpServerSetState(pServer, RTTCPSERVERSTATE_DESTROYING, RTTCPSERVERSTATE_SIGNALING);
                    Assert(fRc); NOREF(fRc);

                    /* server */
                    rtTcpServerDestroyServerSock(SockServer, "Destroyer: server destroying");
                    RTThreadYield();

                    return VINF_SUCCESS;
                }
                break;
            }


            /*
             * Intermediate state.
             */
            case RTTCPSERVERSTATE_STOPPING:
                if (!RTThreadYield())
                    RTThreadSleep(1);
                break;

            /*
             * Just release the handle.
             */
            case RTTCPSERVERSTATE_CREATED:
            case RTTCPSERVERSTATE_STOPPED:
                if (rtTcpServerSetState(pServer, RTTCPSERVERSTATE_FREED, enmState))
                {
                    rtTcpServerDestroyServerSock(SockServer, "Destroyer: server freeing");
                    RTMemFree(pServer);
                    return VINF_TCP_SERVER_STOP;
                }
                break;

            /*
             * Everything else means failure.
             */
            default:
                AssertMsgFailed(("pServer=%p enmState=%d\n", pServer, enmState));
                return VERR_INTERNAL_ERROR;
        }
    }

    AssertMsgFailed(("Giving up! pServer=%p enmState=%d\n", pServer, pServer->enmState));
    rtTcpServerDestroyServerSock(SockServer, "Destroyer: server timeout");
    return VERR_INTERNAL_ERROR;
}


/**
 * Shutdowns the server socket.
 */
static void rtTcpServerDestroyServerSock(RTSOCKET SockServer, const char *pszMsg)
{
    if (SockServer == NIL_RTSOCKET)
        return;
    shutdown(SockServer, SHUT_RDWR);
    rtTcpClose(SockServer, "Destroyer: server destroying");
}



RTR3DECL(int)  RTTcpRead(RTSOCKET Sock, void *pvBuffer, size_t cbBuffer, size_t *pcbRead)
{
    /*
     * Do params checking
     */
    if (!pvBuffer || !cbBuffer)
    {
        AssertMsgFailed(("Invalid params\n"));
        return VERR_INVALID_PARAMETER;
    }

    /*
     * Read loop.
     * If pcbRead is NULL we have to fill the entire buffer!
     */
    size_t cbRead = 0;
    size_t cbToRead = cbBuffer;
    for (;;)
    {
        rtTcpErrorReset();
        ssize_t cbBytesRead = recv(Sock, (char *)pvBuffer + cbRead, cbToRead, MSG_NOSIGNAL);
        if (cbBytesRead < 0)
            return rtTcpError();
        if (cbBytesRead == 0 && rtTcpError())
            return rtTcpError();
        if (pcbRead)
        {
            /* return partial data */
            *pcbRead = cbBytesRead;
            break;
        }

        /* read more? */
        cbRead += cbBytesRead;
        if (cbRead == cbBuffer)
            break;

        /* next */
        cbToRead = cbBuffer - cbRead;
    }

    return VINF_SUCCESS;
}


RTR3DECL(int)  RTTcpWrite(RTSOCKET Sock, const void *pvBuffer, size_t cbBuffer)
{
    do
    {
        ssize_t cbWritten = send(Sock, (const char *)pvBuffer, cbBuffer, MSG_NOSIGNAL);
        if (cbWritten < 0)
            return rtTcpError();
        AssertMsg(cbBuffer >= (size_t)cbWritten, ("Wrote more than we requested!!! cbWritten=%d cbBuffer=%d rtTcpError()=%d\n",
                                                  cbWritten, cbBuffer, rtTcpError()));
        cbBuffer -= cbWritten;
        pvBuffer = (char *)pvBuffer + cbWritten;
    } while (cbBuffer);

    return VINF_SUCCESS;
}


RTR3DECL(int)  RTTcpFlush(RTSOCKET Sock)
{
    int fFlag = 1;
    setsockopt(Sock, IPPROTO_TCP, TCP_NODELAY, (const char *)&fFlag, sizeof(fFlag));
    fFlag = 0;
    setsockopt(Sock, IPPROTO_TCP, TCP_NODELAY, (const char *)&fFlag, sizeof(fFlag));

    return VINF_SUCCESS;
}


RTR3DECL(int)  RTTcpSelectOne(RTSOCKET Sock, unsigned cMillies)
{
    fd_set fdsetR;
    FD_ZERO(&fdsetR);
    FD_SET(Sock, &fdsetR);

    fd_set fdsetE = fdsetR;

    int rc;
    if (cMillies == RT_INDEFINITE_WAIT)
        rc = select(Sock + 1, &fdsetR, NULL, &fdsetE, NULL);
    else
    {
        struct timeval timeout;
        timeout.tv_sec = cMillies / 1000;
        timeout.tv_usec = (cMillies % 1000) * 1000;
        rc = select(Sock + 1, &fdsetR, NULL, &fdsetE, &timeout);
    }
    if (rc > 0)
        return VINF_SUCCESS;
    if (rc == 0)
        return VERR_TIMEOUT;
    return rtTcpError();
}


RTR3DECL(int) RTTcpClientConnect(const char *pszAddress, uint32_t uPort, PRTSOCKET pSock)
{
    int rc;

    /*
     * Do params checking
     */
    AssertReturn(uPort, VERR_INVALID_PARAMETER);
    AssertReturn(VALID_PTR(pszAddress), VERR_INVALID_PARAMETER);

#ifdef RT_OS_WINDOWS
    /*
     * Initialize WinSock and check version.
     */
    WORD    wVersionRequested = MAKEWORD(1, 1);
    WSADATA wsaData;
    rc = WSAStartup(wVersionRequested, &wsaData);
    if (wsaData.wVersion != wVersionRequested)
    {
        AssertMsgFailed(("Wrong winsock version\n"));
        return VERR_NOT_SUPPORTED;
    }
#endif

    /*
     * Resolve the address.
     */
    struct hostent *pHostEnt = NULL;
    pHostEnt = gethostbyname(pszAddress);
    if (!pHostEnt)
    {
        struct in_addr InAddr;
        InAddr.s_addr = inet_addr(pszAddress);
        pHostEnt = gethostbyaddr((char *)&InAddr, 4, AF_INET);
        if (!pHostEnt)
        {
            rc = rtTcpError();
            AssertMsgFailed(("Could not resolve '%s', rc=%Rrc\n", pszAddress, rc));
            return rc;
        }
    }

    /*
     * Create the socket and connect.
     */
    RTSOCKET Sock = socket(PF_INET, SOCK_STREAM, 0);
    if (Sock != -1)
    {
        struct sockaddr_in InAddr = {0};
        InAddr.sin_family = AF_INET;
        InAddr.sin_port = htons(uPort);
        InAddr.sin_addr = *((struct in_addr *)pHostEnt->h_addr);
        if (!connect(Sock, (struct sockaddr *)&InAddr, sizeof(InAddr)))
        {
            *pSock = Sock;
            return VINF_SUCCESS;
        }
        rc = rtTcpError();
        rtTcpClose(Sock, "RTTcpClientConnect");
    }
    else
        rc = rtTcpError();
    return rc;
}


RTR3DECL(int) RTTcpClientClose(RTSOCKET Sock)
{
    return rtTcpClose(Sock, "RTTcpClientClose");
}


/**
 * Internal close function which does all the proper bitching.
 */
static int rtTcpClose(RTSOCKET Sock, const char *pszMsg)
{
    /* ignore nil handles. */
    if (Sock == NIL_RTSOCKET)
        return VINF_SUCCESS;

    /*
     * Attempt to close it.
     */
#ifdef RT_OS_WINDOWS
    int rc = closesocket(Sock);
#else
    int rc = close(Sock);
#endif
    if (!rc)
        return VINF_SUCCESS;
    rc = rtTcpError();
    AssertMsgFailed(("\"%s\": close(%d) -> %Rrc\n", pszMsg, Sock, rc));
    return rc;
}