VirtualBox

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

Last change on this file since 34079 was 33540, checked in by vboxsync, 14 years ago

*: spelling fixes, thanks Timeless!

  • Property svn:eol-style set to native
  • Property svn:keywords set to Id
File size: 35.7 KB
Line 
1/* $Id: tcp.cpp 33540 2010-10-28 09:27:05Z vboxsync $ */
2/** @file
3 * IPRT - TCP/IP.
4 */
5
6/*
7 * Copyright (C) 2006-2010 Oracle Corporation
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
27
28/*******************************************************************************
29* Header Files *
30*******************************************************************************/
31#ifdef RT_OS_WINDOWS
32# include <winsock2.h>
33#else
34# include <sys/types.h>
35# include <sys/socket.h>
36# include <errno.h>
37# include <netinet/in.h>
38# include <netinet/tcp.h>
39# include <arpa/inet.h>
40# include <netdb.h>
41# ifdef FIX_FOR_3_2
42# include <fcntl.h>
43# endif
44#endif
45#include <limits.h>
46
47#include "internal/iprt.h"
48#include <iprt/tcp.h>
49
50#include <iprt/asm.h>
51#include <iprt/assert.h>
52#include <iprt/err.h>
53#include <iprt/mempool.h>
54#include <iprt/mem.h>
55#include <iprt/string.h>
56#include <iprt/socket.h>
57#include <iprt/thread.h>
58#include <iprt/time.h>
59
60#include "internal/magics.h"
61#include "internal/socket.h"
62
63
64/*******************************************************************************
65* Defined Constants And Macros *
66*******************************************************************************/
67/* non-standard linux stuff (it seems). */
68#ifndef MSG_NOSIGNAL
69# define MSG_NOSIGNAL 0
70#endif
71#ifndef SHUT_RDWR
72# ifdef SD_BOTH
73# define SHUT_RDWR SD_BOTH
74# else
75# define SHUT_RDWR 2
76# endif
77#endif
78#ifndef SHUT_WR
79# ifdef SD_SEND
80# define SHUT_WR SD_SEND
81# else
82# define SHUT_WR 1
83# endif
84#endif
85
86/* fixup backlevel OSes. */
87#if defined(RT_OS_OS2) || defined(RT_OS_WINDOWS)
88# define socklen_t int
89#endif
90
91/** How many pending connection. */
92#define RTTCP_SERVER_BACKLOG 10
93
94
95/*******************************************************************************
96* Structures and Typedefs *
97*******************************************************************************/
98/**
99 * TCP Server state.
100 */
101typedef enum RTTCPSERVERSTATE
102{
103 /** Invalid. */
104 RTTCPSERVERSTATE_INVALID = 0,
105 /** Created. */
106 RTTCPSERVERSTATE_CREATED,
107 /** Listener thread is starting up. */
108 RTTCPSERVERSTATE_STARTING,
109 /** Accepting client connections. */
110 RTTCPSERVERSTATE_ACCEPTING,
111 /** Serving a client. */
112 RTTCPSERVERSTATE_SERVING,
113 /** Listener terminating. */
114 RTTCPSERVERSTATE_STOPPING,
115 /** Listener terminated. */
116 RTTCPSERVERSTATE_STOPPED,
117 /** Listener cleans up. */
118 RTTCPSERVERSTATE_DESTROYING
119} RTTCPSERVERSTATE;
120
121/*
122 * Internal representation of the TCP Server handle.
123 */
124typedef struct RTTCPSERVER
125{
126 /** The magic value (RTTCPSERVER_MAGIC). */
127 uint32_t volatile u32Magic;
128 /** The server state. */
129 RTTCPSERVERSTATE volatile enmState;
130 /** The server thread. */
131 RTTHREAD Thread;
132 /** The server socket. */
133 RTSOCKET volatile hServerSocket;
134 /** The socket to the client currently being serviced.
135 * This is NIL_RTSOCKET when no client is serviced. */
136 RTSOCKET volatile hClientSocket;
137 /** The connection function. */
138 PFNRTTCPSERVE pfnServe;
139 /** Argument to pfnServer. */
140 void *pvUser;
141} RTTCPSERVER;
142
143
144/*******************************************************************************
145* Internal Functions *
146*******************************************************************************/
147static DECLCALLBACK(int) rtTcpServerThread(RTTHREAD ThreadSelf, void *pvServer);
148static int rtTcpServerListen(PRTTCPSERVER pServer);
149static int rtTcpServerListenCleanup(PRTTCPSERVER pServer);
150static int rtTcpServerDestroySocket(RTSOCKET volatile *pSockClient, const char *pszMsg);
151static int rtTcpClose(RTSOCKET Sock, const char *pszMsg, bool fTryGracefulShutdown);
152
153
154/**
155 * Atomicly updates a socket variable.
156 * @returns The old handle value.
157 * @param phSock The socket handle variable to update.
158 * @param hSock The new socket handle value.
159 */
160DECLINLINE(RTSOCKET) rtTcpAtomicXchgSock(RTSOCKET volatile *phSock, const RTSOCKET hNew)
161{
162 RTSOCKET hRet;
163 ASMAtomicXchgHandle(phSock, hNew, &hRet);
164 return hRet;
165}
166
167
168/**
169 * Tries to change the TCP server state.
170 */
171DECLINLINE(bool) rtTcpServerTrySetState(PRTTCPSERVER pServer, RTTCPSERVERSTATE enmStateNew, RTTCPSERVERSTATE enmStateOld)
172{
173 bool fRc;
174 ASMAtomicCmpXchgSize(&pServer->enmState, enmStateNew, enmStateOld, fRc);
175 return fRc;
176}
177
178/**
179 * Changes the TCP server state.
180 */
181DECLINLINE(void) rtTcpServerSetState(PRTTCPSERVER pServer, RTTCPSERVERSTATE enmStateNew, RTTCPSERVERSTATE enmStateOld)
182{
183 bool fRc;
184 ASMAtomicCmpXchgSize(&pServer->enmState, enmStateNew, enmStateOld, fRc);
185 Assert(fRc); NOREF(fRc);
186}
187
188
189/**
190 * Closes the a socket (client or server).
191 *
192 * @returns IPRT status code.
193 */
194static int rtTcpServerDestroySocket(RTSOCKET volatile *pSock, const char *pszMsg, bool fTryGracefulShutdown)
195{
196 RTSOCKET hSocket = rtTcpAtomicXchgSock(pSock, NIL_RTSOCKET);
197 if (hSocket != NIL_RTSOCKET)
198 {
199 if (!fTryGracefulShutdown)
200 RTSocketShutdown(hSocket, true /*fRead*/, true /*fWrite*/);
201 return rtTcpClose(hSocket, pszMsg, fTryGracefulShutdown);
202 }
203 return VINF_TCP_SERVER_NO_CLIENT;
204}
205
206
207/**
208 * Create single connection at a time TCP Server in a separate thread.
209 *
210 * The thread will loop accepting connections and call pfnServe for
211 * each of the incoming connections in turn. The pfnServe function can
212 * return VERR_TCP_SERVER_STOP too terminate this loop. RTTcpServerDestroy()
213 * should be used to terminate the server.
214 *
215 * @returns iprt status code.
216 * @param pszAddress The address for creating a listening socket.
217 * If NULL or empty string the server is bound to all interfaces.
218 * @param uPort The port for creating a listening socket.
219 * @param enmType The thread type.
220 * @param pszThrdName The name of the worker thread.
221 * @param pfnServe The function which will serve a new client connection.
222 * @param pvUser User argument passed to pfnServe.
223 * @param ppServer Where to store the serverhandle.
224 */
225RTR3DECL(int) RTTcpServerCreate(const char *pszAddress, unsigned uPort, RTTHREADTYPE enmType, const char *pszThrdName,
226 PFNRTTCPSERVE pfnServe, void *pvUser, PPRTTCPSERVER ppServer)
227{
228 /*
229 * Validate input.
230 */
231 AssertReturn(uPort > 0, VERR_INVALID_PARAMETER);
232 AssertPtrReturn(pfnServe, VERR_INVALID_POINTER);
233 AssertPtrReturn(pszThrdName, VERR_INVALID_POINTER);
234 AssertPtrReturn(ppServer, VERR_INVALID_POINTER);
235
236 /*
237 * Create the server.
238 */
239 PRTTCPSERVER pServer;
240 int rc = RTTcpServerCreateEx(pszAddress, uPort, &pServer);
241 if (RT_SUCCESS(rc))
242 {
243 /*
244 * Create the listener thread.
245 */
246 RTMemPoolRetain(pServer);
247 pServer->enmState = RTTCPSERVERSTATE_STARTING;
248 pServer->pvUser = pvUser;
249 pServer->pfnServe = pfnServe;
250 rc = RTThreadCreate(&pServer->Thread, rtTcpServerThread, pServer, 0, enmType, /*RTTHREADFLAGS_WAITABLE*/0, pszThrdName);
251 if (RT_SUCCESS(rc))
252 {
253 /* done */
254 if (ppServer)
255 *ppServer = pServer;
256 else
257 RTMemPoolRelease(RTMEMPOOL_DEFAULT, pServer);
258 return rc;
259 }
260 RTMemPoolRelease(RTMEMPOOL_DEFAULT, pServer);
261
262 /*
263 * Destroy the server.
264 */
265 rtTcpServerSetState(pServer, RTTCPSERVERSTATE_CREATED, RTTCPSERVERSTATE_STARTING);
266 RTTcpServerDestroy(pServer);
267 }
268
269 return rc;
270}
271
272
273/**
274 * Server thread, loops accepting connections until it's terminated.
275 *
276 * @returns iprt status code. (ignored).
277 * @param ThreadSelf Thread handle.
278 * @param pvServer Server handle.
279 */
280static DECLCALLBACK(int) rtTcpServerThread(RTTHREAD ThreadSelf, void *pvServer)
281{
282 PRTTCPSERVER pServer = (PRTTCPSERVER)pvServer;
283 int rc;
284 if (rtTcpServerTrySetState(pServer, RTTCPSERVERSTATE_ACCEPTING, RTTCPSERVERSTATE_STARTING))
285 rc = rtTcpServerListen(pServer);
286 else
287 rc = rtTcpServerListenCleanup(pServer);
288 RTMemPoolRelease(RTMEMPOOL_DEFAULT, pServer);
289 NOREF(ThreadSelf);
290 return VINF_SUCCESS;
291}
292
293
294/**
295 * Create single connection at a time TCP Server.
296 * The caller must call RTTcpServerListen() to actually start the server.
297 *
298 * @returns iprt status code.
299 * @param pszAddress The address for creating a listening socket.
300 * If NULL the server is bound to all interfaces.
301 * @param uPort The port for creating a listening socket.
302 * @param ppServer Where to store the serverhandle.
303 */
304RTR3DECL(int) RTTcpServerCreateEx(const char *pszAddress, uint32_t uPort, PPRTTCPSERVER ppServer)
305{
306 int rc;
307
308 /*
309 * Validate input.
310 */
311 AssertReturn(uPort > 0, VERR_INVALID_PARAMETER);
312 AssertPtrReturn(ppServer, VERR_INVALID_PARAMETER);
313
314#ifdef RT_OS_WINDOWS
315 /*
316 * Initialize WinSock and check version.
317 */
318 WORD wVersionRequested = MAKEWORD(1, 1);
319 WSADATA wsaData;
320 rc = WSAStartup(wVersionRequested, &wsaData);
321 if (wsaData.wVersion != wVersionRequested)
322 {
323 AssertMsgFailed(("Wrong winsock version\n"));
324 return VERR_NOT_SUPPORTED;
325 }
326#endif
327
328 /*
329 * Get host listening address.
330 */
331 struct hostent *pHostEnt = NULL;
332 if (pszAddress != NULL && *pszAddress)
333 {
334 pHostEnt = gethostbyname(pszAddress);
335 if (!pHostEnt)
336 {
337 struct in_addr InAddr;
338 InAddr.s_addr = inet_addr(pszAddress);
339 pHostEnt = gethostbyaddr((char *)&InAddr, 4, AF_INET);
340 if (!pHostEnt)
341 {
342 rc = rtSocketResolverError();
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->hServerSocket = WaitSock;
394 pServer->hClientSocket = 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->hClientSocket == 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, getting an extra reference to the socket so we can
480 * allow others to close it while we're stuck in rtSocketAccept.
481 */
482 RTTCPSERVERSTATE enmState = pServer->enmState;
483 RTSOCKET hServerSocket;
484 ASMAtomicXchgHandle(&pServer->hServerSocket, NIL_RTSOCKET, &hServerSocket);
485 if (hServerSocket != NIL_RTSOCKET)
486 {
487 RTSocketRetain(hServerSocket);
488 ASMAtomicWriteHandle(&pServer->hServerSocket, hServerSocket);
489 }
490 if ( enmState != RTTCPSERVERSTATE_ACCEPTING
491 && enmState != RTTCPSERVERSTATE_SERVING)
492 {
493 RTSocketRelease(hServerSocket);
494 return rtTcpServerListenCleanup(pServer);
495 }
496 if (!rtTcpServerTrySetState(pServer, RTTCPSERVERSTATE_ACCEPTING, enmState))
497 {
498 RTSocketRelease(hServerSocket);
499 continue;
500 }
501
502 /*
503 * Accept connection.
504 */
505 struct sockaddr_in RemoteAddr;
506 size_t cbRemoteAddr = sizeof(RemoteAddr);
507 RTSOCKET hClientSocket;
508 RT_ZERO(RemoteAddr);
509 int rc = rtSocketAccept(hServerSocket, &hClientSocket, (struct sockaddr *)&RemoteAddr, &cbRemoteAddr);
510 RTSocketRelease(hServerSocket);
511 if (RT_FAILURE(rc))
512 {
513 /* These are typical for what can happen during destruction. */
514 if ( rc == VERR_INVALID_HANDLE
515 || rc == VERR_INVALID_PARAMETER
516 || rc == VERR_NET_NOT_SOCKET)
517 return rtTcpServerListenCleanup(pServer);
518 continue;
519 }
520 RTSocketSetInheritance(hClientSocket, false /*fInheritable*/);
521
522 /*
523 * Run a pfnServe callback.
524 */
525 if (!rtTcpServerTrySetState(pServer, RTTCPSERVERSTATE_SERVING, RTTCPSERVERSTATE_ACCEPTING))
526 {
527 rtTcpClose(hClientSocket, "rtTcpServerListen", true /*fTryGracefulShutdown*/);
528 return rtTcpServerListenCleanup(pServer);
529 }
530 RTSocketRetain(hClientSocket);
531 rtTcpAtomicXchgSock(&pServer->hClientSocket, hClientSocket);
532 rc = pServer->pfnServe(hClientSocket, pServer->pvUser);
533 rtTcpServerDestroySocket(&pServer->hClientSocket, "Listener: client (secondary)", true /*fTryGracefulShutdown*/);
534 RTSocketRelease(hClientSocket);
535
536 /*
537 * Stop the server?
538 */
539 if (rc == VERR_TCP_SERVER_STOP)
540 {
541 if (rtTcpServerTrySetState(pServer, RTTCPSERVERSTATE_STOPPING, RTTCPSERVERSTATE_SERVING))
542 {
543 /*
544 * Reset the server socket and change the state to stopped. After that state change
545 * we cannot safely access the handle so we'll have to return here.
546 */
547 hServerSocket = rtTcpAtomicXchgSock(&pServer->hServerSocket, NIL_RTSOCKET);
548 rtTcpServerSetState(pServer, RTTCPSERVERSTATE_STOPPED, RTTCPSERVERSTATE_STOPPING);
549 rtTcpClose(hServerSocket, "Listener: server stopped", false /*fTryGracefulShutdown*/);
550 }
551 else
552 rtTcpServerListenCleanup(pServer); /* ignore rc */
553 return rc;
554 }
555 }
556}
557
558
559/**
560 * Clean up after listener.
561 */
562static int rtTcpServerListenCleanup(PRTTCPSERVER pServer)
563{
564 /*
565 * Close the server socket, the client one shouldn't be set.
566 */
567 rtTcpServerDestroySocket(&pServer->hServerSocket, "ListenCleanup", false /*fTryGracefulShutdown*/);
568 Assert(pServer->hClientSocket == NIL_RTSOCKET);
569
570 /*
571 * Figure the return code and make sure the state is OK.
572 */
573 RTTCPSERVERSTATE enmState = pServer->enmState;
574 switch (enmState)
575 {
576 case RTTCPSERVERSTATE_STOPPING:
577 case RTTCPSERVERSTATE_STOPPED:
578 return VERR_TCP_SERVER_SHUTDOWN;
579
580 case RTTCPSERVERSTATE_ACCEPTING:
581 rtTcpServerTrySetState(pServer, RTTCPSERVERSTATE_STOPPED, enmState);
582 return VERR_TCP_SERVER_DESTROYED;
583
584 case RTTCPSERVERSTATE_DESTROYING:
585 return VERR_TCP_SERVER_DESTROYED;
586
587 case RTTCPSERVERSTATE_STARTING:
588 case RTTCPSERVERSTATE_SERVING:
589 default:
590 AssertMsgFailedReturn(("pServer=%p enmState=%d\n", pServer, enmState), VERR_INTERNAL_ERROR_4);
591 }
592}
593
594
595/**
596 * Listen and accept one incoming connection.
597 *
598 * This is an alternative to RTTcpServerListen for the use the callbacks are not
599 * possible.
600 *
601 * @returns IPRT status code.
602 * @retval VERR_TCP_SERVER_SHUTDOWN if shut down by RTTcpServerShutdown.
603 * @retval VERR_INTERRUPTED if the listening was interrupted.
604 *
605 * @param pServer The server handle as returned from RTTcpServerCreateEx().
606 * @param phClientSocket Where to return the socket handle to the client
607 * connection (on success only). This must be closed
608 * by calling RTTcpServerDisconnectClient2().
609 */
610RTR3DECL(int) RTTcpServerListen2(PRTTCPSERVER pServer, PRTSOCKET phClientSocket)
611{
612 /*
613 * Validate input and retain the instance.
614 */
615 AssertPtrReturn(phClientSocket, VERR_INVALID_HANDLE);
616 *phClientSocket = NIL_RTSOCKET;
617 AssertReturn(pServer->u32Magic == RTTCPSERVER_MAGIC, VERR_INVALID_HANDLE);
618 AssertReturn(RTMemPoolRetain(pServer) != UINT32_MAX, VERR_INVALID_HANDLE);
619
620 int rc = VERR_INVALID_STATE;
621 for (;;)
622 {
623 /*
624 * Change state, getting an extra reference to the socket so we can
625 * allow others to close it while we're stuck in rtSocketAccept.
626 */
627 RTTCPSERVERSTATE enmState = pServer->enmState;
628 RTSOCKET hServerSocket;
629 ASMAtomicXchgHandle(&pServer->hServerSocket, NIL_RTSOCKET, &hServerSocket);
630 if (hServerSocket != NIL_RTSOCKET)
631 {
632 RTSocketRetain(hServerSocket);
633 ASMAtomicWriteHandle(&pServer->hServerSocket, hServerSocket);
634 }
635 if ( enmState != RTTCPSERVERSTATE_SERVING
636 && enmState != RTTCPSERVERSTATE_CREATED)
637 {
638 RTSocketRelease(hServerSocket);
639 return rtTcpServerListenCleanup(pServer);
640 }
641 if (!rtTcpServerTrySetState(pServer, RTTCPSERVERSTATE_ACCEPTING, enmState))
642 {
643 RTSocketRelease(hServerSocket);
644 continue;
645 }
646 Assert(!pServer->pfnServe);
647 Assert(!pServer->pvUser);
648 Assert(pServer->Thread == NIL_RTTHREAD);
649 Assert(pServer->hClientSocket == NIL_RTSOCKET);
650
651 /*
652 * Accept connection.
653 */
654 struct sockaddr_in RemoteAddr;
655 size_t cbRemoteAddr = sizeof(RemoteAddr);
656 RTSOCKET hClientSocket;
657 RT_ZERO(RemoteAddr);
658 rc = rtSocketAccept(hServerSocket, &hClientSocket, (struct sockaddr *)&RemoteAddr, &cbRemoteAddr);
659 RTSocketRelease(hServerSocket);
660 if (RT_FAILURE(rc))
661 {
662 if (!rtTcpServerTrySetState(pServer, RTTCPSERVERSTATE_CREATED, RTTCPSERVERSTATE_ACCEPTING))
663 rc = rtTcpServerListenCleanup(pServer);
664 if (RT_FAILURE(rc))
665 break;
666 continue;
667 }
668 RTSocketSetInheritance(hClientSocket, false /*fInheritable*/);
669
670 /*
671 * Chance to the 'serving' state and return the socket.
672 */
673 if (rtTcpServerTrySetState(pServer, RTTCPSERVERSTATE_SERVING, RTTCPSERVERSTATE_ACCEPTING))
674 {
675 *phClientSocket = hClientSocket;
676 rc = VINF_SUCCESS;
677 }
678 else
679 {
680 rtTcpClose(hClientSocket, "RTTcpServerListen2", true /*fTryGracefulShutdown*/);
681 rc = rtTcpServerListenCleanup(pServer);
682 }
683 break;
684 }
685
686 RTMemPoolRelease(RTMEMPOOL_DEFAULT, pServer);
687 return rc;
688}
689
690
691/**
692 * Terminate the open connection to the server.
693 *
694 * @returns iprt status code.
695 * @param pServer Handle to the server.
696 */
697RTR3DECL(int) RTTcpServerDisconnectClient(PRTTCPSERVER pServer)
698{
699 /*
700 * Validate input and retain the instance.
701 */
702 AssertPtrReturn(pServer, VERR_INVALID_HANDLE);
703 AssertReturn(pServer->u32Magic == RTTCPSERVER_MAGIC, VERR_INVALID_HANDLE);
704 AssertReturn(RTMemPoolRetain(pServer) != UINT32_MAX, VERR_INVALID_HANDLE);
705
706 int rc = rtTcpServerDestroySocket(&pServer->hClientSocket, "DisconnectClient: client", true /*fTryGracefulShutdown*/);
707
708 RTMemPoolRelease(RTMEMPOOL_DEFAULT, pServer);
709 return rc;
710}
711
712
713/**
714 * Terminates an open client connect when using RTTcpListen2
715 *
716 * @returns IPRT status code.
717 * @param hClientSocket The client socket handle. This will be invalid upon
718 * return, whether successful or not. NIL is quietly
719 * ignored (VINF_SUCCESS).
720 */
721RTR3DECL(int) RTTcpServerDisconnectClient2(RTSOCKET hClientSocket)
722{
723 return rtTcpClose(hClientSocket, "RTTcpServerDisconnectClient2", true /*fTryGracefulShutdown*/);
724}
725
726
727/**
728 * Shuts down the server, leaving client connections open.
729 *
730 * @returns IPRT status code.
731 * @param pServer Handle to the server.
732 */
733RTR3DECL(int) RTTcpServerShutdown(PRTTCPSERVER pServer)
734{
735 /*
736 * Validate input and retain the instance.
737 */
738 AssertPtrReturn(pServer, VERR_INVALID_HANDLE);
739 AssertReturn(pServer->u32Magic == RTTCPSERVER_MAGIC, VERR_INVALID_HANDLE);
740 AssertReturn(RTMemPoolRetain(pServer) != UINT32_MAX, VERR_INVALID_HANDLE);
741
742 /*
743 * Try change the state to stopping, then replace and destroy the server socket.
744 */
745 for (;;)
746 {
747 RTTCPSERVERSTATE enmState = pServer->enmState;
748 if ( enmState != RTTCPSERVERSTATE_ACCEPTING
749 && enmState != RTTCPSERVERSTATE_SERVING)
750 {
751 RTMemPoolRelease(RTMEMPOOL_DEFAULT, pServer);
752 switch (enmState)
753 {
754 case RTTCPSERVERSTATE_CREATED:
755 case RTTCPSERVERSTATE_STARTING:
756 default:
757 AssertMsgFailed(("%d\n", enmState));
758 return VERR_INVALID_STATE;
759
760 case RTTCPSERVERSTATE_STOPPING:
761 case RTTCPSERVERSTATE_STOPPED:
762 return VINF_SUCCESS;
763
764 case RTTCPSERVERSTATE_DESTROYING:
765 return VERR_TCP_SERVER_DESTROYED;
766 }
767 }
768 if (rtTcpServerTrySetState(pServer, RTTCPSERVERSTATE_STOPPING, enmState))
769 {
770 rtTcpServerDestroySocket(&pServer->hServerSocket, "RTTcpServerShutdown", false /*fTryGracefulShutdown*/);
771 rtTcpServerSetState(pServer, RTTCPSERVERSTATE_STOPPED, RTTCPSERVERSTATE_STOPPING);
772
773 RTMemPoolRelease(RTMEMPOOL_DEFAULT, pServer);
774 return VINF_SUCCESS;
775 }
776 }
777}
778
779
780/**
781 * Closes down and frees a TCP Server.
782 * This will also terminate any open connections to the server.
783 *
784 * @returns iprt status code.
785 * @param pServer Handle to the server.
786 */
787RTR3DECL(int) RTTcpServerDestroy(PRTTCPSERVER pServer)
788{
789 /*
790 * Validate input and retain the instance.
791 */
792 AssertPtrReturn(pServer, VERR_INVALID_HANDLE);
793 AssertReturn(pServer->u32Magic == RTTCPSERVER_MAGIC, VERR_INVALID_HANDLE);
794 AssertReturn(RTMemPoolRetain(pServer) != UINT32_MAX, VERR_INVALID_HANDLE); /* paranoia */
795
796 /*
797 * Move the state along so the listener can figure out what's going on.
798 */
799 for (;;)
800 {
801 bool fDestroyable;
802 RTTCPSERVERSTATE enmState = pServer->enmState;
803 switch (enmState)
804 {
805 case RTTCPSERVERSTATE_STARTING:
806 case RTTCPSERVERSTATE_ACCEPTING:
807 case RTTCPSERVERSTATE_SERVING:
808 case RTTCPSERVERSTATE_CREATED:
809 case RTTCPSERVERSTATE_STOPPED:
810 fDestroyable = rtTcpServerTrySetState(pServer, RTTCPSERVERSTATE_DESTROYING, enmState);
811 break;
812
813 /* destroyable states */
814 case RTTCPSERVERSTATE_STOPPING:
815 fDestroyable = true;
816 break;
817
818 /*
819 * Everything else means user or internal misbehavior.
820 */
821 default:
822 AssertMsgFailed(("pServer=%p enmState=%d\n", pServer, enmState));
823 RTMemPoolRelease(RTMEMPOOL_DEFAULT, pServer);
824 return VERR_INTERNAL_ERROR;
825 }
826 if (fDestroyable)
827 break;
828 }
829
830 /*
831 * Destroy it.
832 */
833 ASMAtomicWriteU32(&pServer->u32Magic, ~RTTCPSERVER_MAGIC);
834 rtTcpServerDestroySocket(&pServer->hServerSocket, "Destroyer: server", false /*fTryGracefulShutdown*/);
835 rtTcpServerDestroySocket(&pServer->hClientSocket, "Destroyer: client", true /*fTryGracefulShutdown*/);
836
837 /*
838 * Release it.
839 */
840 RTMemPoolRelease(RTMEMPOOL_DEFAULT, pServer);
841 RTMemPoolRelease(RTMEMPOOL_DEFAULT, pServer);
842 return VINF_SUCCESS;
843}
844
845
846RTR3DECL(int) RTTcpClientConnect(const char *pszAddress, uint32_t uPort, PRTSOCKET pSock)
847{
848 int rc;
849
850 /*
851 * Validate input.
852 */
853 AssertReturn(uPort > 0, VERR_INVALID_PARAMETER);
854 AssertPtrReturn(pszAddress, VERR_INVALID_POINTER);
855
856#ifdef RT_OS_WINDOWS
857 /*
858 * Initialize WinSock and check version.
859 */
860 WORD wVersionRequested = MAKEWORD(1, 1);
861 WSADATA wsaData;
862 rc = WSAStartup(wVersionRequested, &wsaData);
863 if (wsaData.wVersion != wVersionRequested)
864 {
865 AssertMsgFailed(("Wrong winsock version\n"));
866 return VERR_NOT_SUPPORTED;
867 }
868#endif
869
870 /*
871 * Resolve the address.
872 */
873 struct hostent *pHostEnt = NULL;
874 pHostEnt = gethostbyname(pszAddress);
875 if (!pHostEnt)
876 {
877 struct in_addr InAddr;
878 InAddr.s_addr = inet_addr(pszAddress);
879 pHostEnt = gethostbyaddr((char *)&InAddr, 4, AF_INET);
880 if (!pHostEnt)
881 {
882 rc = rtSocketResolverError();
883 AssertMsgFailed(("Could not resolve '%s', rc=%Rrc\n", pszAddress, rc));
884 return rc;
885 }
886 }
887
888 /*
889 * Create the socket and connect.
890 */
891 RTSOCKET Sock;
892 rc = rtSocketCreate(&Sock, PF_INET, SOCK_STREAM, 0);
893 if (RT_SUCCESS(rc))
894 {
895 RTSocketSetInheritance(Sock, false /*fInheritable*/);
896
897 struct sockaddr_in InAddr;
898 RT_ZERO(InAddr);
899 InAddr.sin_family = AF_INET;
900 InAddr.sin_port = htons(uPort);
901 InAddr.sin_addr = *((struct in_addr *)pHostEnt->h_addr);
902 rc = rtSocketConnect(Sock, (struct sockaddr *)&InAddr, sizeof(InAddr));
903 if (RT_SUCCESS(rc))
904 {
905 *pSock = Sock;
906 return VINF_SUCCESS;
907 }
908
909 rtTcpClose(Sock, "RTTcpClientConnect", false /*fTryGracefulShutdown*/);
910 }
911 return rc;
912}
913
914
915RTR3DECL(int) RTTcpClientClose(RTSOCKET Sock)
916{
917 return rtTcpClose(Sock, "RTTcpClientClose", true /*fTryGracefulShutdown*/);
918}
919
920
921RTR3DECL(int) RTTcpClientCloseEx(RTSOCKET Sock, bool fGracefulShutdown)
922{
923 return rtTcpClose(Sock, "RTTcpClientCloseEx", fGracefulShutdown);
924}
925
926
927#ifdef FIX_FOR_3_2
928/**
929 * Changes the blocking mode of the socket.
930 *
931 * @returns 0 on success, -1 on failure.
932 * @param hSocket The socket to work on.
933 * @param fBlocking The desired mode of operation.
934 */
935static int rtTcpSetBlockingMode(RTHCUINTPTR hSocket, bool fBlocking)
936{
937 int rc = VINF_SUCCESS;
938#ifdef RT_OS_WINDOWS
939 u_long uBlocking = fBlocking ? 0 : 1;
940 if (ioctlsocket(hSocket, FIONBIO, &uBlocking))
941 return -1;
942
943#else
944 int fFlags = fcntl(hSocket, F_GETFL, 0);
945 if (fFlags == -1)
946 return -1;
947
948 if (fBlocking)
949 fFlags &= ~O_NONBLOCK;
950 else
951 fFlags |= O_NONBLOCK;
952 if (fcntl(hSocket, F_SETFL, fFlags) == -1)
953 return -1;
954#endif
955
956 return 0;
957}
958#endif
959
960
961/**
962 * Internal close function which does all the proper bitching.
963 */
964static int rtTcpClose(RTSOCKET Sock, const char *pszMsg, bool fTryGracefulShutdown)
965{
966 int rc;
967
968 /* ignore nil handles. */
969 if (Sock == NIL_RTSOCKET)
970 return VINF_SUCCESS;
971
972 /*
973 * Try to gracefully shut it down.
974 */
975 if (fTryGracefulShutdown)
976 {
977 rc = RTSocketShutdown(Sock, false /*fRead*/, true /*fWrite*/);
978#ifdef FIX_FOR_3_2
979 RTHCUINTPTR hNative = RTSocketToNative(Sock);
980 if (RT_SUCCESS(rc) && rtTcpSetBlockingMode(hNative, false /*fBlocking*/) == 0)
981#else
982 if (RT_SUCCESS(rc))
983#endif
984 {
985
986 size_t cbReceived = 0;
987 uint64_t u64Start = RTTimeMilliTS();
988 while ( cbReceived < _1G
989 && RTTimeMilliTS() - u64Start < 30000)
990 {
991#ifdef FIX_FOR_3_2
992 fd_set FdSetR;
993 FD_ZERO(&FdSetR);
994 FD_SET(hNative, &FdSetR);
995
996 fd_set FdSetE;
997 FD_ZERO(&FdSetE);
998 FD_SET(hNative, &FdSetE);
999
1000 struct timeval TvTimeout;
1001 TvTimeout.tv_sec = 1;
1002 TvTimeout.tv_usec = 0;
1003 rc = select(hNative + 1, &FdSetR, NULL, &FdSetE, &TvTimeout);
1004 if (rc == 0)
1005 continue;
1006 if (rc < 0)
1007 break;
1008 if (FD_ISSET(hNative, &FdSetE))
1009 break;
1010#else
1011 uint32_t fEvents;
1012 rc = RTSocketSelectOneEx(Sock, RTSOCKET_EVT_READ | RTSOCKET_EVT_ERROR, &fEvents, 1000);
1013 if (rc == VERR_TIMEOUT)
1014 continue;
1015 if (RT_FAILURE(rc))
1016 break;
1017 if (fEvents & RTSOCKET_EVT_ERROR)
1018 break;
1019#endif
1020
1021 char abBitBucket[16*_1K];
1022#ifdef FIX_FOR_3_2
1023 ssize_t cbRead = recv(hNative, &abBitBucket[0], sizeof(abBitBucket), MSG_NOSIGNAL);
1024 if (cbRead == 0)
1025 break; /* orderly shutdown in progress */
1026 if (cbRead < 0 && errno != EAGAIN)
1027 break; /* some kind of error, never mind which... */
1028#else
1029 size_t cbRead;
1030 rc = RTSocketReadNB(Sock, &abBitBucket[0], sizeof(abBitBucket), &cbRead);
1031 if (RT_FAILURE(rc))
1032 break; /* some kind of error, never mind which... */
1033 if (rc != VINF_TRY_AGAIN && !cbRead)
1034 break; /* orderly shutdown in progress */
1035#endif
1036
1037 cbReceived += cbRead;
1038 }
1039 }
1040 }
1041
1042 /*
1043 * Close the socket handle (drops our reference to it).
1044 */
1045 return RTSocketClose(Sock);
1046}
1047
1048
1049RTR3DECL(int) RTTcpRead(RTSOCKET Sock, void *pvBuffer, size_t cbBuffer, size_t *pcbRead)
1050{
1051 return RTSocketRead(Sock, pvBuffer, cbBuffer, pcbRead);
1052}
1053
1054
1055RTR3DECL(int) RTTcpWrite(RTSOCKET Sock, const void *pvBuffer, size_t cbBuffer)
1056{
1057 return RTSocketWrite(Sock, pvBuffer, cbBuffer);
1058}
1059
1060
1061RTR3DECL(int) RTTcpFlush(RTSOCKET Sock)
1062{
1063 int fFlag = 1;
1064 int rc = rtSocketSetOpt(Sock, IPPROTO_TCP, TCP_NODELAY, &fFlag, sizeof(fFlag));
1065 if (RT_SUCCESS(rc))
1066 {
1067 fFlag = 0;
1068 rc = rtSocketSetOpt(Sock, IPPROTO_TCP, TCP_NODELAY, &fFlag, sizeof(fFlag));
1069 }
1070 return rc;
1071}
1072
1073
1074RTR3DECL(int) RTTcpSetSendCoalescing(RTSOCKET Sock, bool fEnable)
1075{
1076 int fFlag = fEnable ? 0 : 1;
1077 return rtSocketSetOpt(Sock, IPPROTO_TCP, TCP_NODELAY, &fFlag, sizeof(fFlag));
1078}
1079
1080
1081RTR3DECL(int) RTTcpSelectOne(RTSOCKET Sock, RTMSINTERVAL cMillies)
1082{
1083 return RTSocketSelectOne(Sock, cMillies);
1084}
1085
1086
1087RTR3DECL(int) RTTcpSelectOneEx(RTSOCKET Sock, uint32_t fEvents, uint32_t *pfEvents,
1088 RTMSINTERVAL cMillies)
1089{
1090 return RTSocketSelectOneEx(Sock, fEvents, pfEvents, cMillies);
1091}
1092
1093
1094RTR3DECL(int) RTTcpGetLocalAddress(RTSOCKET Sock, PRTNETADDR pAddr)
1095{
1096 return RTSocketGetLocalAddress(Sock, pAddr);
1097}
1098
1099
1100RTR3DECL(int) RTTcpGetPeerAddress(RTSOCKET Sock, PRTNETADDR pAddr)
1101{
1102 return RTSocketGetPeerAddress(Sock, pAddr);
1103}
1104
1105
1106RTR3DECL(int) RTTcpSgWrite(RTSOCKET Sock, PCRTSGBUF pSgBuf)
1107{
1108 return RTSocketSgWrite(Sock, pSgBuf);
1109}
1110
1111
1112RTR3DECL(int) RTTcpSgWriteL(RTSOCKET hSocket, size_t cSegs, ...)
1113{
1114 va_list va;
1115 va_start(va, cSegs);
1116 int rc = RTSocketSgWriteLV(hSocket, cSegs, va);
1117 va_end(va);
1118 return rc;
1119}
1120
1121
1122RTR3DECL(int) RTTcpSgWriteLV(RTSOCKET hSocket, size_t cSegs, va_list va)
1123{
1124 return RTSocketSgWriteLV(hSocket, cSegs, va);
1125}
1126
1127
1128RTR3DECL(int) RTTcpReadNB(RTSOCKET Sock, void *pvBuffer, size_t cbBuffer, size_t *pcbRead)
1129{
1130 return RTSocketReadNB(Sock, pvBuffer, cbBuffer, pcbRead);
1131}
1132
1133
1134RTR3DECL(int) RTTcpWriteNB(RTSOCKET Sock, const void *pvBuffer, size_t cbBuffer, size_t *pcbWritten)
1135{
1136 return RTSocketWriteNB(Sock, pvBuffer, cbBuffer, pcbWritten);
1137}
1138
1139
1140RTR3DECL(int) RTTcpSgWriteNB(RTSOCKET Sock, PCRTSGBUF pSgBuf, size_t *pcbWritten)
1141{
1142 return RTSocketSgWriteNB(Sock, pSgBuf, pcbWritten);
1143}
1144
1145
1146RTR3DECL(int) RTTcpSgWriteLNB(RTSOCKET hSocket, size_t cSegs, size_t *pcbWritten, ...)
1147{
1148 va_list va;
1149 va_start(va, pcbWritten);
1150 int rc = RTSocketSgWriteLVNB(hSocket, cSegs, pcbWritten, va);
1151 va_end(va);
1152 return rc;
1153}
1154
1155
1156RTR3DECL(int) RTTcpSgWriteLVNB(RTSOCKET hSocket, size_t cSegs, size_t *pcbWritten, va_list va)
1157{
1158 return RTSocketSgWriteLVNB(hSocket, cSegs, pcbWritten, va);
1159}
1160
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