VirtualBox

source: vbox/trunk/src/VBox/Runtime/r3/tcp.cpp@ 27667

Last change on this file since 27667 was 27506, checked in by vboxsync, 15 years ago

tcp.cpp: drop some of the includes.

  • Property svn:eol-style set to native
  • Property svn:keywords set to Id
File size: 30.7 KB
Line 
1/* $Id: tcp.cpp 27506 2010-03-18 21:25:08Z vboxsync $ */
2/** @file
3 * IPRT - TCP/IP.
4 */
5
6/*
7 * Copyright (C) 2006-2010 Sun Microsystems, Inc.
8 *
9 * This file is part of VirtualBox Open Source Edition (OSE), as
10 * available from http://www.virtualbox.org. This file is free software;
11 * you can redistribute it and/or modify it under the terms of the GNU
12 * General Public License (GPL) as published by the Free Software
13 * Foundation, in version 2 as it comes in the "COPYING" file of the
14 * VirtualBox OSE distribution. VirtualBox OSE is distributed in the
15 * hope that it will be useful, but WITHOUT ANY WARRANTY of any kind.
16 *
17 * The contents of this file may alternatively be used under the terms
18 * of the Common Development and Distribution License Version 1.0
19 * (CDDL) only, as it comes in the "COPYING.CDDL" file of the
20 * VirtualBox OSE distribution, in which case the provisions of the
21 * CDDL are applicable instead of those of the GPL.
22 *
23 * You may elect to license modified versions of this file under the
24 * terms and conditions of either the GPL or the CDDL or both.
25 *
26 * Please contact Sun Microsystems, Inc., 4150 Network Circle, Santa
27 * Clara, CA 95054 USA or visit http://www.sun.com if you need
28 * additional information or have any questions.
29 */
30
31
32/*******************************************************************************
33* Header Files *
34*******************************************************************************/
35#ifdef RT_OS_WINDOWS
36# include <winsock2.h>
37#else /* !RT_OS_WINDOWS */
38# include <errno.h>
39# include <netinet/in.h>
40# include <netinet/tcp.h>
41# include <arpa/inet.h>
42# include <netdb.h>
43#endif /* !RT_OS_WINDOWS */
44#include <limits.h>
45
46#include "internal/iprt.h"
47#include <iprt/tcp.h>
48
49#include <iprt/asm.h>
50#include <iprt/assert.h>
51#include <iprt/err.h>
52#include <iprt/mempool.h>
53#include <iprt/mem.h>
54#include <iprt/string.h>
55#include <iprt/socket.h>
56#include <iprt/thread.h>
57#include <iprt/time.h>
58
59#include "internal/magics.h"
60#include "internal/socket.h"
61
62
63/*******************************************************************************
64* Defined Constants And Macros *
65*******************************************************************************/
66/* non-standard linux stuff (it seems). */
67#ifndef MSG_NOSIGNAL
68# define MSG_NOSIGNAL 0
69#endif
70#ifndef SHUT_RDWR
71# ifdef SD_BOTH
72# define SHUT_RDWR SD_BOTH
73# else
74# define SHUT_RDWR 2
75# endif
76#endif
77#ifndef SHUT_WR
78# ifdef SD_SEND
79# define SHUT_WR SD_SEND
80# else
81# define SHUT_WR 1
82# endif
83#endif
84
85/* fixup backlevel OSes. */
86#if defined(RT_OS_OS2) || defined(RT_OS_WINDOWS)
87# define socklen_t int
88#endif
89
90/** How many pending connection. */
91#define RTTCP_SERVER_BACKLOG 10
92
93
94/*******************************************************************************
95* Structures and Typedefs *
96*******************************************************************************/
97/**
98 * TCP Server state.
99 */
100typedef enum RTTCPSERVERSTATE
101{
102 /** Invalid. */
103 RTTCPSERVERSTATE_INVALID = 0,
104 /** Created. */
105 RTTCPSERVERSTATE_CREATED,
106 /** Listener thread is starting up. */
107 RTTCPSERVERSTATE_STARTING,
108 /** Accepting client connections. */
109 RTTCPSERVERSTATE_ACCEPTING,
110 /** Serving a client. */
111 RTTCPSERVERSTATE_SERVING,
112 /** Listener terminating. */
113 RTTCPSERVERSTATE_STOPPING,
114 /** Listener terminated. */
115 RTTCPSERVERSTATE_STOPPED,
116 /** Listener cleans up. */
117 RTTCPSERVERSTATE_DESTROYING
118} RTTCPSERVERSTATE;
119
120/*
121 * Internal representation of the TCP Server handle.
122 */
123typedef struct RTTCPSERVER
124{
125 /** The magic value (RTTCPSERVER_MAGIC). */
126 uint32_t volatile u32Magic;
127 /** The server state. */
128 RTTCPSERVERSTATE volatile enmState;
129 /** The server thread. */
130 RTTHREAD Thread;
131 /** The server socket. */
132 RTSOCKET volatile SockServer;
133 /** The socket to the client currently being serviced.
134 * This is NIL_RTSOCKET when no client is serviced. */
135 RTSOCKET volatile SockClient;
136 /** The connection function. */
137 PFNRTTCPSERVE pfnServe;
138 /** Argument to pfnServer. */
139 void *pvUser;
140} RTTCPSERVER;
141
142
143/*******************************************************************************
144* Internal Functions *
145*******************************************************************************/
146static DECLCALLBACK(int) rtTcpServerThread(RTTHREAD ThreadSelf, void *pvServer);
147static int rtTcpServerListen(PRTTCPSERVER pServer);
148static int rtTcpServerListenCleanup(PRTTCPSERVER pServer);
149static int rtTcpServerDestroySocket(RTSOCKET volatile *pSockClient, const char *pszMsg);
150static int rtTcpClose(RTSOCKET Sock, const char *pszMsg, bool fTryGracefulShutdown);
151
152
153/**
154 * Atomicly updates a socket variable.
155 * @returns The old handle value.
156 * @param phSock The socket handle variable to update.
157 * @param hSock The new socket handle value.
158 */
159DECLINLINE(RTSOCKET) rtTcpAtomicXchgSock(RTSOCKET volatile *phSock, const RTSOCKET hNew)
160{
161 RTSOCKET hRet;
162 ASMAtomicXchgHandle(phSock, hNew, &hRet);
163 return hRet;
164}
165
166
167/**
168 * Tries to change the TCP server state.
169 */
170DECLINLINE(bool) rtTcpServerTrySetState(PRTTCPSERVER pServer, RTTCPSERVERSTATE enmStateNew, RTTCPSERVERSTATE enmStateOld)
171{
172 bool fRc;
173 ASMAtomicCmpXchgSize(&pServer->enmState, enmStateNew, enmStateOld, fRc);
174 return fRc;
175}
176
177/**
178 * Changes the TCP server state.
179 */
180DECLINLINE(void) rtTcpServerSetState(PRTTCPSERVER pServer, RTTCPSERVERSTATE enmStateNew, RTTCPSERVERSTATE enmStateOld)
181{
182 bool fRc;
183 ASMAtomicCmpXchgSize(&pServer->enmState, enmStateNew, enmStateOld, fRc);
184 Assert(fRc); NOREF(fRc);
185}
186
187
188/**
189 * Closes the a socket (client or server).
190 *
191 * @returns IPRT status code.
192 */
193static int rtTcpServerDestroySocket(RTSOCKET volatile *pSock, const char *pszMsg, bool fTryGracefulShutdown)
194{
195 RTSOCKET hSocket = rtTcpAtomicXchgSock(pSock, NIL_RTSOCKET);
196 if (hSocket != NIL_RTSOCKET)
197 {
198 if (!fTryGracefulShutdown)
199 RTSocketShutdown(hSocket, true /*fRead*/, true /*fWrite*/);
200 return rtTcpClose(hSocket, pszMsg, fTryGracefulShutdown);
201 }
202 return VINF_TCP_SERVER_NO_CLIENT;
203}
204
205
206/**
207 * Create single connection at a time TCP Server in a separate thread.
208 *
209 * The thread will loop accepting connections and call pfnServe for
210 * each of the incoming connections in turn. The pfnServe function can
211 * return VERR_TCP_SERVER_STOP too terminate this loop. RTTcpServerDestroy()
212 * should be used to terminate the server.
213 *
214 * @returns iprt status code.
215 * @param pszAddress The address for creating a listening socket.
216 * If NULL or empty string the server is bound to all interfaces.
217 * @param uPort The port for creating a listening socket.
218 * @param enmType The thread type.
219 * @param pszThrdName The name of the worker thread.
220 * @param pfnServe The function which will serve a new client connection.
221 * @param pvUser User argument passed to pfnServe.
222 * @param ppServer Where to store the serverhandle.
223 */
224RTR3DECL(int) RTTcpServerCreate(const char *pszAddress, unsigned uPort, RTTHREADTYPE enmType, const char *pszThrdName,
225 PFNRTTCPSERVE pfnServe, void *pvUser, PPRTTCPSERVER ppServer)
226{
227 /*
228 * Validate input.
229 */
230 AssertReturn(uPort > 0, VERR_INVALID_PARAMETER);
231 AssertPtrReturn(pfnServe, VERR_INVALID_POINTER);
232 AssertPtrReturn(pszThrdName, VERR_INVALID_POINTER);
233 AssertPtrReturn(ppServer, VERR_INVALID_POINTER);
234
235 /*
236 * Create the server.
237 */
238 PRTTCPSERVER pServer;
239 int rc = RTTcpServerCreateEx(pszAddress, uPort, &pServer);
240 if (RT_SUCCESS(rc))
241 {
242 /*
243 * Create the listener thread.
244 */
245 RTMemPoolRetain(pServer);
246 pServer->enmState = RTTCPSERVERSTATE_STARTING;
247 pServer->pvUser = pvUser;
248 pServer->pfnServe = pfnServe;
249 rc = RTThreadCreate(&pServer->Thread, rtTcpServerThread, pServer, 0, enmType, /*RTTHREADFLAGS_WAITABLE*/0, pszThrdName);
250 if (RT_SUCCESS(rc))
251 {
252 /* done */
253 if (ppServer)
254 *ppServer = pServer;
255 else
256 RTMemPoolRelease(RTMEMPOOL_DEFAULT, pServer);
257 return rc;
258 }
259 RTMemPoolRelease(RTMEMPOOL_DEFAULT, pServer);
260
261 /*
262 * Destroy the server.
263 */
264 rtTcpServerSetState(pServer, RTTCPSERVERSTATE_CREATED, RTTCPSERVERSTATE_STARTING);
265 RTTcpServerDestroy(pServer);
266 }
267
268 return rc;
269}
270
271
272/**
273 * Server thread, loops accepting connections until it's terminated.
274 *
275 * @returns iprt status code. (ignored).
276 * @param ThreadSelf Thread handle.
277 * @param pvServer Server handle.
278 */
279static DECLCALLBACK(int) rtTcpServerThread(RTTHREAD ThreadSelf, void *pvServer)
280{
281 PRTTCPSERVER pServer = (PRTTCPSERVER)pvServer;
282 int rc;
283 if (rtTcpServerTrySetState(pServer, RTTCPSERVERSTATE_ACCEPTING, RTTCPSERVERSTATE_STARTING))
284 rc = rtTcpServerListen(pServer);
285 else
286 rc = rtTcpServerListenCleanup(pServer);
287 RTMemPoolRelease(RTMEMPOOL_DEFAULT, pServer);
288 NOREF(ThreadSelf);
289 return VINF_SUCCESS;
290}
291
292
293/**
294 * Create single connection at a time TCP Server.
295 * The caller must call RTTcpServerListen() to actually start the server.
296 *
297 * @returns iprt status code.
298 * @param pszAddress The address for creating a listening socket.
299 * If NULL the server is bound to all interfaces.
300 * @param uPort The port for creating a listening socket.
301 * @param ppServer Where to store the serverhandle.
302 */
303RTR3DECL(int) RTTcpServerCreateEx(const char *pszAddress, uint32_t uPort, PPRTTCPSERVER ppServer)
304{
305 int rc;
306
307 /*
308 * Validate input.
309 */
310 AssertReturn(uPort > 0, VERR_INVALID_PARAMETER);
311 AssertPtrReturn(ppServer, VERR_INVALID_PARAMETER);
312
313#ifdef RT_OS_WINDOWS
314 /*
315 * Initialize WinSock and check version.
316 */
317 WORD wVersionRequested = MAKEWORD(1, 1);
318 WSADATA wsaData;
319 rc = WSAStartup(wVersionRequested, &wsaData);
320 if (wsaData.wVersion != wVersionRequested)
321 {
322 AssertMsgFailed(("Wrong winsock version\n"));
323 return VERR_NOT_SUPPORTED;
324 }
325#endif
326
327 /*
328 * Get host listening address.
329 */
330 struct hostent *pHostEnt = NULL;
331 if (pszAddress != NULL && *pszAddress)
332 {
333 pHostEnt = gethostbyname(pszAddress);
334 if (!pHostEnt)
335 {
336 struct in_addr InAddr;
337 InAddr.s_addr = inet_addr(pszAddress);
338 pHostEnt = gethostbyaddr((char *)&InAddr, 4, AF_INET);
339 if (!pHostEnt)
340 {
341 rc = rtSocketResolverError();
342 AssertMsgFailed(("Could not get host address rc=%Rrc\n", rc));
343 return rc;
344 }
345 }
346 }
347
348 /*
349 * Setting up socket.
350 */
351 RTSOCKET WaitSock;
352 rc = rtSocketCreate(&WaitSock, AF_INET, SOCK_STREAM, IPPROTO_TCP);
353 if (RT_SUCCESS(rc))
354 {
355 RTSocketSetInheritance(WaitSock, false /*fInheritable*/);
356
357 /*
358 * Set socket options.
359 */
360 int fFlag = 1;
361 if (!rtSocketSetOpt(WaitSock, SOL_SOCKET, SO_REUSEADDR, &fFlag, sizeof(fFlag)))
362 {
363 /*
364 * Set socket family, address and port.
365 */
366 struct sockaddr_in LocalAddr;
367 RT_ZERO(LocalAddr);
368 LocalAddr.sin_family = AF_INET;
369 LocalAddr.sin_port = htons(uPort);
370 /* if address not specified, use INADDR_ANY. */
371 if (!pHostEnt)
372 LocalAddr.sin_addr.s_addr = INADDR_ANY;
373 else
374 LocalAddr.sin_addr = *((struct in_addr *)pHostEnt->h_addr);
375
376 /*
377 * Bind a name to a socket and set it listening for connections.
378 */
379 rc = rtSocketBind(WaitSock, (struct sockaddr *)&LocalAddr, sizeof(LocalAddr));
380 if (RT_SUCCESS(rc))
381 rc = rtSocketListen(WaitSock, RTTCP_SERVER_BACKLOG);
382 if (RT_SUCCESS(rc))
383 {
384 /*
385 * Create the server handle.
386 */
387 PRTTCPSERVER pServer = (PRTTCPSERVER)RTMemPoolAlloc(RTMEMPOOL_DEFAULT, sizeof(*pServer));
388 if (pServer)
389 {
390 pServer->u32Magic = RTTCPSERVER_MAGIC;
391 pServer->enmState = RTTCPSERVERSTATE_CREATED;
392 pServer->Thread = NIL_RTTHREAD;
393 pServer->SockServer = WaitSock;
394 pServer->SockClient = NIL_RTSOCKET;
395 pServer->pfnServe = NULL;
396 pServer->pvUser = NULL;
397 *ppServer = pServer;
398 return VINF_SUCCESS;
399 }
400
401 /* bail out */
402 rc = VERR_NO_MEMORY;
403 }
404 }
405 else
406 AssertMsgFailed(("rtSocketSetOpt: %Rrc\n", rc));
407 rtTcpClose(WaitSock, "RTServerCreateEx", false /*fTryGracefulShutdown*/);
408 }
409
410 return rc;
411}
412
413
414/**
415 * Listen for incoming connections.
416 *
417 * The function will loop accepting connections and call pfnServe for
418 * each of the incoming connections in turn. The pfnServe function can
419 * return VERR_TCP_SERVER_STOP too terminate this loop. A stopped server
420 * can only be destroyed.
421 *
422 * @returns IPRT status code.
423 * @retval VERR_TCP_SERVER_STOP if stopped by pfnServe.
424 * @retval VERR_TCP_SERVER_SHUTDOWN if shut down by RTTcpServerShutdown.
425 *
426 * @param pServer The server handle as returned from RTTcpServerCreateEx().
427 * @param pfnServe The function which will serve a new client connection.
428 * @param pvUser User argument passed to pfnServe.
429 */
430RTR3DECL(int) RTTcpServerListen(PRTTCPSERVER pServer, PFNRTTCPSERVE pfnServe, void *pvUser)
431{
432 /*
433 * Validate input and retain the instance.
434 */
435 AssertPtrReturn(pfnServe, VERR_INVALID_POINTER);
436 AssertPtrReturn(pServer, VERR_INVALID_HANDLE);
437 AssertReturn(pServer->u32Magic == RTTCPSERVER_MAGIC, VERR_INVALID_HANDLE);
438 AssertReturn(RTMemPoolRetain(pServer) != UINT32_MAX, VERR_INVALID_HANDLE);
439
440 int rc = VERR_INVALID_STATE;
441 if (rtTcpServerTrySetState(pServer, RTTCPSERVERSTATE_ACCEPTING, RTTCPSERVERSTATE_CREATED))
442 {
443 Assert(!pServer->pfnServe);
444 Assert(!pServer->pvUser);
445 Assert(pServer->Thread == NIL_RTTHREAD);
446 Assert(pServer->SockClient == NIL_RTSOCKET);
447
448 pServer->pfnServe = pfnServe;
449 pServer->pvUser = pvUser;
450 pServer->Thread = RTThreadSelf();
451 Assert(pServer->Thread != NIL_RTTHREAD);
452 rc = rtTcpServerListen(pServer);
453 }
454 else
455 {
456 AssertMsgFailed(("enmState=%d\n", pServer->enmState));
457 rc = VERR_INVALID_STATE;
458 }
459 RTMemPoolRelease(RTMEMPOOL_DEFAULT, pServer);
460 return rc;
461}
462
463
464/**
465 * Internal worker common for RTTcpServerListen and the thread created by
466 * RTTcpServerCreate().
467 *
468 * The caller makes sure it has its own memory reference and releases it upon
469 * return.
470 */
471static int rtTcpServerListen(PRTTCPSERVER pServer)
472{
473 /*
474 * Accept connection loop.
475 */
476 for (;;)
477 {
478 /*
479 * Change state.
480 */
481 RTTCPSERVERSTATE enmState = pServer->enmState;
482 RTSOCKET SockServer = pServer->SockServer;
483 if ( enmState != RTTCPSERVERSTATE_ACCEPTING
484 && enmState != RTTCPSERVERSTATE_SERVING)
485 return rtTcpServerListenCleanup(pServer);
486 if (!rtTcpServerTrySetState(pServer, RTTCPSERVERSTATE_ACCEPTING, enmState))
487 continue;
488
489 /*
490 * Accept connection.
491 */
492 struct sockaddr_in RemoteAddr;
493 size_t cbRemoteAddr = sizeof(RemoteAddr);
494 RTSOCKET Socket;
495 RT_ZERO(RemoteAddr);
496 int rc = rtSocketAccept(SockServer, &Socket, (struct sockaddr *)&RemoteAddr, &cbRemoteAddr);
497 if (RT_FAILURE(rc))
498 {
499 /* These are typical for what can happen during destruction. */
500 if ( rc == VERR_INVALID_HANDLE
501 || rc == VERR_INVALID_PARAMETER
502 || rc == VERR_NET_NOT_SOCKET)
503 return rtTcpServerListenCleanup(pServer);
504 continue;
505 }
506 RTSocketSetInheritance(Socket, false /*fInheritable*/);
507
508 /*
509 * Run a pfnServe callback.
510 */
511 if (!rtTcpServerTrySetState(pServer, RTTCPSERVERSTATE_SERVING, RTTCPSERVERSTATE_ACCEPTING))
512 {
513 rtTcpClose(Socket, "rtTcpServerListen", true /*fTryGracefulShutdown*/);
514 return rtTcpServerListenCleanup(pServer);
515 }
516 rtTcpAtomicXchgSock(&pServer->SockClient, Socket);
517 rc = pServer->pfnServe(Socket, pServer->pvUser);
518 rtTcpServerDestroySocket(&pServer->SockClient, "Listener: client", true /*fTryGracefulShutdown*/);
519
520 /*
521 * Stop the server?
522 */
523 if (rc == VERR_TCP_SERVER_STOP)
524 {
525 if (rtTcpServerTrySetState(pServer, RTTCPSERVERSTATE_STOPPING, RTTCPSERVERSTATE_SERVING))
526 {
527 /*
528 * Reset the server socket and change the state to stopped. After that state change
529 * we cannot safely access the handle so we'll have to return here.
530 */
531 SockServer = rtTcpAtomicXchgSock(&pServer->SockServer, NIL_RTSOCKET);
532 rtTcpServerSetState(pServer, RTTCPSERVERSTATE_STOPPED, RTTCPSERVERSTATE_STOPPING);
533 rtTcpClose(SockServer, "Listener: server stopped", false /*fTryGracefulShutdown*/);
534 }
535 else
536 rtTcpServerListenCleanup(pServer); /* ignore rc */
537 return rc;
538 }
539 }
540}
541
542
543/**
544 * Clean up after listener.
545 */
546static int rtTcpServerListenCleanup(PRTTCPSERVER pServer)
547{
548 /*
549 * Close the server socket, the client one shouldn't be set.
550 */
551 rtTcpServerDestroySocket(&pServer->SockServer, "ListenCleanup", false /*fTryGracefulShutdown*/);
552 Assert(pServer->SockClient == NIL_RTSOCKET);
553
554 /*
555 * Figure the return code and make sure the state is OK.
556 */
557 RTTCPSERVERSTATE enmState = pServer->enmState;
558 switch (enmState)
559 {
560 case RTTCPSERVERSTATE_STOPPING:
561 case RTTCPSERVERSTATE_STOPPED:
562 return VERR_TCP_SERVER_SHUTDOWN;
563
564 case RTTCPSERVERSTATE_ACCEPTING:
565 rtTcpServerTrySetState(pServer, RTTCPSERVERSTATE_STOPPED, enmState);
566 return VERR_TCP_SERVER_DESTROYED;
567
568 case RTTCPSERVERSTATE_DESTROYING:
569 return VERR_TCP_SERVER_DESTROYED;
570
571 case RTTCPSERVERSTATE_STARTING:
572 case RTTCPSERVERSTATE_SERVING:
573 default:
574 AssertMsgFailedReturn(("pServer=%p enmState=%d\n", pServer, enmState), VERR_INTERNAL_ERROR_4);
575 }
576}
577
578
579/**
580 * Listen and accept one incomming connection.
581 *
582 * This is an alternative to RTTcpServerListen for the use the callbacks are not
583 * possible.
584 *
585 * @returns IPRT status code.
586 * @retval VERR_TCP_SERVER_SHUTDOWN if shut down by RTTcpServerShutdown.
587 * @retval VERR_INTERRUPTED if the listening was interrupted.
588 *
589 * @param pServer The server handle as returned from RTTcpServerCreateEx().
590 * @param pSockClient Where to return the socket handle to the client
591 * connection (on success only). Use
592 * RTTcpServerDisconnectClient() to clean it, this must
593 * be done before the next call to RTTcpServerListen2.
594 *
595 * @todo This can easily be extended to support multiple connections by
596 * adding a new state and a RTTcpServerDisconnectClient variant for
597 * closing client sockets.
598 */
599RTR3DECL(int) RTTcpServerListen2(PRTTCPSERVER pServer, PRTSOCKET pSockClient)
600{
601 /*
602 * Validate input and retain the instance.
603 */
604 AssertPtrReturn(pSockClient, VERR_INVALID_HANDLE);
605 *pSockClient = NIL_RTSOCKET;
606 AssertReturn(pServer->u32Magic == RTTCPSERVER_MAGIC, VERR_INVALID_HANDLE);
607 AssertReturn(RTMemPoolRetain(pServer) != UINT32_MAX, VERR_INVALID_HANDLE);
608
609 int rc = VERR_INVALID_STATE;
610 for (;;)
611 {
612 /*
613 * Change state to accepting.
614 */
615 RTTCPSERVERSTATE enmState = pServer->enmState;
616 RTSOCKET SockServer = pServer->SockServer;
617 if ( enmState != RTTCPSERVERSTATE_SERVING
618 && enmState != RTTCPSERVERSTATE_CREATED)
619 {
620 rc = rtTcpServerListenCleanup(pServer);
621 break;
622 }
623 if (!rtTcpServerTrySetState(pServer, RTTCPSERVERSTATE_ACCEPTING, enmState))
624 continue;
625 Assert(!pServer->pfnServe);
626 Assert(!pServer->pvUser);
627 Assert(pServer->Thread == NIL_RTTHREAD);
628 Assert(pServer->SockClient == NIL_RTSOCKET);
629
630 /*
631 * Accept connection.
632 */
633 struct sockaddr_in RemoteAddr;
634 size_t cbRemoteAddr = sizeof(RemoteAddr);
635 RTSOCKET Socket;
636 RT_ZERO(RemoteAddr);
637 rc = rtSocketAccept(SockServer, &Socket, (struct sockaddr *)&RemoteAddr, &cbRemoteAddr);
638 if (RT_FAILURE(rc))
639 {
640 if (!rtTcpServerTrySetState(pServer, RTTCPSERVERSTATE_CREATED, RTTCPSERVERSTATE_ACCEPTING))
641 rc = rtTcpServerListenCleanup(pServer);
642 if (RT_FAILURE(rc))
643 break;
644 continue;
645 }
646 RTSocketSetInheritance(Socket, false /*fInheritable*/);
647
648 /*
649 * Chance to the 'serving' state and return the socket.
650 */
651 if (rtTcpServerTrySetState(pServer, RTTCPSERVERSTATE_SERVING, RTTCPSERVERSTATE_ACCEPTING))
652 {
653 RTSOCKET OldSocket = rtTcpAtomicXchgSock(&pServer->SockClient, Socket);
654 Assert(OldSocket == NIL_RTSOCKET); NOREF(OldSocket);
655 *pSockClient = Socket;
656 rc = VINF_SUCCESS;
657 }
658 else
659 {
660 rtTcpClose(Socket, "RTTcpServerListen2", true /*fTryGracefulShutdown*/);
661 rc = rtTcpServerListenCleanup(pServer);
662 }
663 break;
664 }
665
666 RTMemPoolRelease(RTMEMPOOL_DEFAULT, pServer);
667 return rc;
668}
669
670
671/**
672 * Terminate the open connection to the server.
673 *
674 * @returns iprt status code.
675 * @param pServer Handle to the server.
676 */
677RTR3DECL(int) RTTcpServerDisconnectClient(PRTTCPSERVER pServer)
678{
679 /*
680 * Validate input and retain the instance.
681 */
682 AssertPtrReturn(pServer, VERR_INVALID_HANDLE);
683 AssertReturn(pServer->u32Magic == RTTCPSERVER_MAGIC, VERR_INVALID_HANDLE);
684 AssertReturn(RTMemPoolRetain(pServer) != UINT32_MAX, VERR_INVALID_HANDLE);
685
686 int rc = rtTcpServerDestroySocket(&pServer->SockClient, "DisconnectClient: client", true /*fTryGracefulShutdown*/);
687
688 RTMemPoolRelease(RTMEMPOOL_DEFAULT, pServer);
689 return rc;
690}
691
692
693/**
694 * Shuts down the server, leaving client connections open.
695 *
696 * @returns IPRT status code.
697 * @param pServer Handle to the server.
698 */
699RTR3DECL(int) RTTcpServerShutdown(PRTTCPSERVER pServer)
700{
701 /*
702 * Validate input and retain the instance.
703 */
704 AssertPtrReturn(pServer, VERR_INVALID_HANDLE);
705 AssertReturn(pServer->u32Magic == RTTCPSERVER_MAGIC, VERR_INVALID_HANDLE);
706 AssertReturn(RTMemPoolRetain(pServer) != UINT32_MAX, VERR_INVALID_HANDLE);
707
708 /*
709 * Try change the state to stopping, then replace and destroy the server socket.
710 */
711 for (;;)
712 {
713 RTTCPSERVERSTATE enmState = pServer->enmState;
714 if ( enmState != RTTCPSERVERSTATE_ACCEPTING
715 && enmState != RTTCPSERVERSTATE_SERVING)
716 {
717 RTMemPoolRelease(RTMEMPOOL_DEFAULT, pServer);
718 switch (enmState)
719 {
720 case RTTCPSERVERSTATE_CREATED:
721 case RTTCPSERVERSTATE_STARTING:
722 default:
723 AssertMsgFailed(("%d\n", enmState));
724 return VERR_INVALID_STATE;
725
726 case RTTCPSERVERSTATE_STOPPING:
727 case RTTCPSERVERSTATE_STOPPED:
728 return VINF_SUCCESS;
729
730 case RTTCPSERVERSTATE_DESTROYING:
731 return VERR_TCP_SERVER_DESTROYED;
732 }
733 }
734 if (rtTcpServerTrySetState(pServer, RTTCPSERVERSTATE_STOPPING, enmState))
735 {
736 rtTcpServerDestroySocket(&pServer->SockServer, "RTTcpServerShutdown", false /*fTryGracefulShutdown*/);
737 rtTcpServerSetState(pServer, RTTCPSERVERSTATE_STOPPED, RTTCPSERVERSTATE_STOPPING);
738
739 RTMemPoolRelease(RTMEMPOOL_DEFAULT, pServer);
740 return VINF_SUCCESS;
741 }
742 }
743}
744
745
746/**
747 * Closes down and frees a TCP Server.
748 * This will also terminate any open connections to the server.
749 *
750 * @returns iprt status code.
751 * @param pServer Handle to the server.
752 */
753RTR3DECL(int) RTTcpServerDestroy(PRTTCPSERVER pServer)
754{
755 /*
756 * Validate input and retain the instance.
757 */
758 AssertPtrReturn(pServer, VERR_INVALID_HANDLE);
759 AssertReturn(pServer->u32Magic == RTTCPSERVER_MAGIC, VERR_INVALID_HANDLE);
760 AssertReturn(RTMemPoolRetain(pServer) != UINT32_MAX, VERR_INVALID_HANDLE); /* paranoia */
761
762 /*
763 * Move the state along so the listener can figure out what's going on.
764 */
765 for (;;)
766 {
767 bool fDestroyable;
768 RTTCPSERVERSTATE enmState = pServer->enmState;
769 switch (enmState)
770 {
771 case RTTCPSERVERSTATE_STARTING:
772 case RTTCPSERVERSTATE_ACCEPTING:
773 case RTTCPSERVERSTATE_SERVING:
774 case RTTCPSERVERSTATE_CREATED:
775 case RTTCPSERVERSTATE_STOPPED:
776 fDestroyable = rtTcpServerTrySetState(pServer, RTTCPSERVERSTATE_DESTROYING, enmState);
777 break;
778
779 /* destroyable states */
780 case RTTCPSERVERSTATE_STOPPING:
781 fDestroyable = true;
782 break;
783
784 /*
785 * Everything else means user or internal misbehavior.
786 */
787 default:
788 AssertMsgFailed(("pServer=%p enmState=%d\n", pServer, enmState));
789 RTMemPoolRelease(RTMEMPOOL_DEFAULT, pServer);
790 return VERR_INTERNAL_ERROR;
791 }
792 if (fDestroyable)
793 break;
794 }
795
796 /*
797 * Destroy it.
798 */
799 ASMAtomicWriteU32(&pServer->u32Magic, ~RTTCPSERVER_MAGIC);
800 rtTcpServerDestroySocket(&pServer->SockServer, "Destroyer: server", false /*fTryGracefulShutdown*/);
801 rtTcpServerDestroySocket(&pServer->SockClient, "Destroyer: client", true /*fTryGracefulShutdown*/);
802
803 /*
804 * Release it.
805 */
806 RTMemPoolRelease(RTMEMPOOL_DEFAULT, pServer);
807 RTMemPoolRelease(RTMEMPOOL_DEFAULT, pServer);
808 return VINF_SUCCESS;
809}
810
811
812RTR3DECL(int) RTTcpClientConnect(const char *pszAddress, uint32_t uPort, PRTSOCKET pSock)
813{
814 int rc;
815
816 /*
817 * Validate input.
818 */
819 AssertReturn(uPort > 0, VERR_INVALID_PARAMETER);
820 AssertPtrReturn(pszAddress, VERR_INVALID_POINTER);
821
822#ifdef RT_OS_WINDOWS
823 /*
824 * Initialize WinSock and check version.
825 */
826 WORD wVersionRequested = MAKEWORD(1, 1);
827 WSADATA wsaData;
828 rc = WSAStartup(wVersionRequested, &wsaData);
829 if (wsaData.wVersion != wVersionRequested)
830 {
831 AssertMsgFailed(("Wrong winsock version\n"));
832 return VERR_NOT_SUPPORTED;
833 }
834#endif
835
836 /*
837 * Resolve the address.
838 */
839 struct hostent *pHostEnt = NULL;
840 pHostEnt = gethostbyname(pszAddress);
841 if (!pHostEnt)
842 {
843 struct in_addr InAddr;
844 InAddr.s_addr = inet_addr(pszAddress);
845 pHostEnt = gethostbyaddr((char *)&InAddr, 4, AF_INET);
846 if (!pHostEnt)
847 {
848 rc = rtSocketResolverError();
849 AssertMsgFailed(("Could not resolve '%s', rc=%Rrc\n", pszAddress, rc));
850 return rc;
851 }
852 }
853
854 /*
855 * Create the socket and connect.
856 */
857 RTSOCKET Sock;
858 rc = rtSocketCreate(&Sock, PF_INET, SOCK_STREAM, 0);
859 if (RT_SUCCESS(rc))
860 {
861 RTSocketSetInheritance(Sock, false /*fInheritable*/);
862
863 struct sockaddr_in InAddr;
864 RT_ZERO(InAddr);
865 InAddr.sin_family = AF_INET;
866 InAddr.sin_port = htons(uPort);
867 InAddr.sin_addr = *((struct in_addr *)pHostEnt->h_addr);
868 rc = rtSocketConnect(Sock, (struct sockaddr *)&InAddr, sizeof(InAddr));
869 if (RT_SUCCESS(rc))
870 {
871 *pSock = Sock;
872 return VINF_SUCCESS;
873 }
874
875 rtTcpClose(Sock, "RTTcpClientConnect", false /*fTryGracefulShutdown*/);
876 }
877 return rc;
878}
879
880
881RTR3DECL(int) RTTcpClientClose(RTSOCKET Sock)
882{
883 return rtTcpClose(Sock, "RTTcpClientClose", true /*fTryGracefulShutdown*/);
884}
885
886
887/**
888 * Internal close function which does all the proper bitching.
889 */
890static int rtTcpClose(RTSOCKET Sock, const char *pszMsg, bool fTryGracefulShutdown)
891{
892 int rc;
893
894 /* ignore nil handles. */
895 if (Sock == NIL_RTSOCKET)
896 return VINF_SUCCESS;
897
898 /*
899 * Try to gracefully shut it down.
900 */
901 if (fTryGracefulShutdown)
902 {
903 rc = RTSocketShutdown(Sock, false /*fRead*/, true /*fWrite*/);
904 if (RT_SUCCESS(rc))
905 {
906 uint64_t u64Start = RTTimeMilliTS();
907 for (;;)
908 {
909 rc = RTSocketSelectOne(Sock, 1000);
910 if (rc == VERR_TIMEOUT)
911 {
912 if (RTTimeMilliTS() - u64Start > 30000)
913 break;
914 }
915 else if (rc != VINF_SUCCESS)
916 break;
917 {
918 char abBitBucket[16*_1K];
919 ssize_t cbBytesRead = recv(RTSocketToNative(Sock), &abBitBucket[0], sizeof(abBitBucket), MSG_NOSIGNAL);
920 if (cbBytesRead == 0)
921 break; /* orderly shutdown in progress */
922 if (cbBytesRead < 0)
923 break; /* some kind of error, never mind which... */
924 }
925 } /* forever */
926 }
927 }
928
929 /*
930 * Destroy the socket handle.
931 */
932 return RTSocketDestroy(Sock);
933}
934
935
936RTR3DECL(int) RTTcpRead(RTSOCKET Sock, void *pvBuffer, size_t cbBuffer, size_t *pcbRead)
937{
938 return RTSocketRead(Sock, pvBuffer, cbBuffer, pcbRead);
939}
940
941
942RTR3DECL(int) RTTcpWrite(RTSOCKET Sock, const void *pvBuffer, size_t cbBuffer)
943{
944 return RTSocketWrite(Sock, pvBuffer, cbBuffer);
945}
946
947
948RTR3DECL(int) RTTcpFlush(RTSOCKET Sock)
949{
950
951 int fFlag = 1;
952 int rc = rtSocketSetOpt(Sock, IPPROTO_TCP, TCP_NODELAY, &fFlag, sizeof(fFlag));
953 if (RT_SUCCESS(rc))
954 {
955 fFlag = 0;
956 rc = rtSocketSetOpt(Sock, IPPROTO_TCP, TCP_NODELAY, &fFlag, sizeof(fFlag));
957 }
958 return rc;
959}
960
961
962RTR3DECL(int) RTTcpSelectOne(RTSOCKET Sock, RTMSINTERVAL cMillies)
963{
964 return RTSocketSelectOne(Sock, cMillies);
965}
966
967
968RTR3DECL(int) RTTcpGetLocalAddress(RTSOCKET Sock, PRTNETADDR pAddr)
969{
970 return RTSocketGetLocalAddress(Sock, pAddr);
971}
972
973
974RTR3DECL(int) RTTcpGetPeerAddress(RTSOCKET Sock, PRTNETADDR pAddr)
975{
976 return RTSocketGetPeerAddress(Sock, pAddr);
977}
978
Note: See TracBrowser for help on using the repository browser.

© 2024 Oracle Support Privacy / Do Not Sell My Info Terms of Use Trademark Policy Automated Access Etiquette