VirtualBox

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

Last change on this file was 100172, checked in by vboxsync, 12 months ago

IPRT: tcp.h+tcp.cpp,socket.h+socket.cpp: Add RTTcpSetKeepAlive().
Follow-up build fix to address operating system releases which may
define TCP_KEEPALIVE but not TCP_KEEPINTVL and/or TCP_KEEPCNT such as
Solaris 11.3.

  • Property svn:eol-style set to native
  • Property svn:keywords set to Id Revision
File size: 34.9 KB
RevLine 
[1]1/* $Id: tcp.cpp 100172 2023-06-13 21:58:48Z vboxsync $ */
2/** @file
[8245]3 * IPRT - TCP/IP.
[1]4 */
5
6/*
[98103]7 * Copyright (C) 2006-2023 Oracle and/or its affiliates.
[1]8 *
[96407]9 * This file is part of VirtualBox base platform packages, as
10 * available from https://www.virtualbox.org.
[5999]11 *
[96407]12 * This program is free software; you can redistribute it and/or
13 * modify it under the terms of the GNU General Public License
14 * as published by the Free Software Foundation, in version 3 of the
15 * License.
16 *
17 * This program is distributed in the hope that it will be useful, but
18 * WITHOUT ANY WARRANTY; without even the implied warranty of
19 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
20 * General Public License for more details.
21 *
22 * You should have received a copy of the GNU General Public License
23 * along with this program; if not, see <https://www.gnu.org/licenses>.
24 *
[5999]25 * The contents of this file may alternatively be used under the terms
26 * of the Common Development and Distribution License Version 1.0
[96407]27 * (CDDL), a copy of it is provided in the "COPYING.CDDL" file included
28 * in the VirtualBox distribution, in which case the provisions of the
[5999]29 * CDDL are applicable instead of those of the GPL.
30 *
31 * You may elect to license modified versions of this file under the
32 * terms and conditions of either the GPL or the CDDL or both.
[96407]33 *
34 * SPDX-License-Identifier: GPL-3.0-only OR CDDL-1.0
[1]35 */
36
37
[57358]38/*********************************************************************************************************************************
39* Header Files *
40*********************************************************************************************************************************/
[3672]41#ifdef RT_OS_WINDOWS
[62592]42# include <iprt/win/winsock2.h>
[27770]43#else
44# include <sys/types.h>
45# include <sys/socket.h>
[27759]46# include <errno.h>
47# include <netinet/in.h>
48# include <netinet/tcp.h>
49# include <arpa/inet.h>
50# include <netdb.h>
[32810]51# ifdef FIX_FOR_3_2
52# include <fcntl.h>
53# endif
[27770]54#endif
[26683]55#include <limits.h>
[1]56
[23625]57#include "internal/iprt.h"
[1]58#include <iprt/tcp.h>
[23625]59
60#include <iprt/asm.h>
[1]61#include <iprt/assert.h>
62#include <iprt/err.h>
[39801]63#include <iprt/log.h>
[23625]64#include <iprt/mempool.h>
[27497]65#include <iprt/mem.h>
[1]66#include <iprt/string.h>
[27503]67#include <iprt/socket.h>
[23625]68#include <iprt/thread.h>
[24204]69#include <iprt/time.h>
[1]70
[23625]71#include "internal/magics.h"
[27503]72#include "internal/socket.h"
[1]73
[23625]74
[57358]75/*********************************************************************************************************************************
76* Defined Constants And Macros *
77*********************************************************************************************************************************/
[1]78/* non-standard linux stuff (it seems). */
79#ifndef MSG_NOSIGNAL
[23625]80# define MSG_NOSIGNAL 0
[1]81#endif
82#ifndef SHUT_RDWR
83# ifdef SD_BOTH
[23625]84# define SHUT_RDWR SD_BOTH
[1]85# else
[23625]86# define SHUT_RDWR 2
[1]87# endif
88#endif
[24204]89#ifndef SHUT_WR
90# ifdef SD_SEND
91# define SHUT_WR SD_SEND
92# else
93# define SHUT_WR 1
94# endif
95#endif
[1]96
97/* fixup backlevel OSes. */
[3672]98#if defined(RT_OS_OS2) || defined(RT_OS_WINDOWS)
[23625]99# define socklen_t int
[1]100#endif
101
[23625]102/** How many pending connection. */
103#define RTTCP_SERVER_BACKLOG 10
[1]104
105
[57358]106/*********************************************************************************************************************************
107* Structures and Typedefs *
108*********************************************************************************************************************************/
[1]109/**
110 * TCP Server state.
111 */
112typedef enum RTTCPSERVERSTATE
113{
114 /** Invalid. */
115 RTTCPSERVERSTATE_INVALID = 0,
116 /** Created. */
117 RTTCPSERVERSTATE_CREATED,
118 /** Listener thread is starting up. */
119 RTTCPSERVERSTATE_STARTING,
120 /** Accepting client connections. */
121 RTTCPSERVERSTATE_ACCEPTING,
122 /** Serving a client. */
123 RTTCPSERVERSTATE_SERVING,
124 /** Listener terminating. */
125 RTTCPSERVERSTATE_STOPPING,
126 /** Listener terminated. */
127 RTTCPSERVERSTATE_STOPPED,
128 /** Listener cleans up. */
[23625]129 RTTCPSERVERSTATE_DESTROYING
[1]130} RTTCPSERVERSTATE;
131
132/*
133 * Internal representation of the TCP Server handle.
134 */
135typedef struct RTTCPSERVER
136{
[23625]137 /** The magic value (RTTCPSERVER_MAGIC). */
138 uint32_t volatile u32Magic;
[1]139 /** The server state. */
140 RTTCPSERVERSTATE volatile enmState;
141 /** The server thread. */
142 RTTHREAD Thread;
143 /** The server socket. */
[27787]144 RTSOCKET volatile hServerSocket;
[1]145 /** The socket to the client currently being serviced.
146 * This is NIL_RTSOCKET when no client is serviced. */
[27787]147 RTSOCKET volatile hClientSocket;
[1]148 /** The connection function. */
149 PFNRTTCPSERVE pfnServe;
150 /** Argument to pfnServer. */
151 void *pvUser;
152} RTTCPSERVER;
153
154
[57358]155/*********************************************************************************************************************************
156* Internal Functions *
157*********************************************************************************************************************************/
[1]158static DECLCALLBACK(int) rtTcpServerThread(RTTHREAD ThreadSelf, void *pvServer);
[23625]159static int rtTcpServerListen(PRTTCPSERVER pServer);
[27288]160static int rtTcpServerListenCleanup(PRTTCPSERVER pServer);
[24204]161static int rtTcpClose(RTSOCKET Sock, const char *pszMsg, bool fTryGracefulShutdown);
[1]162
163
164/**
165 * Atomicly updates a socket variable.
[27500]166 * @returns The old handle value.
167 * @param phSock The socket handle variable to update.
[57944]168 * @param hNew The new socket handle value.
[1]169 */
[27500]170DECLINLINE(RTSOCKET) rtTcpAtomicXchgSock(RTSOCKET volatile *phSock, const RTSOCKET hNew)
[1]171{
[27500]172 RTSOCKET hRet;
173 ASMAtomicXchgHandle(phSock, hNew, &hRet);
174 return hRet;
[1]175}
176
177
178/**
[23625]179 * Tries to change the TCP server state.
[1]180 */
[23625]181DECLINLINE(bool) rtTcpServerTrySetState(PRTTCPSERVER pServer, RTTCPSERVERSTATE enmStateNew, RTTCPSERVERSTATE enmStateOld)
[1]182{
183 bool fRc;
184 ASMAtomicCmpXchgSize(&pServer->enmState, enmStateNew, enmStateOld, fRc);
185 return fRc;
186}
187
[23625]188/**
189 * Changes the TCP server state.
190 */
191DECLINLINE(void) rtTcpServerSetState(PRTTCPSERVER pServer, RTTCPSERVERSTATE enmStateNew, RTTCPSERVERSTATE enmStateOld)
192{
193 bool fRc;
194 ASMAtomicCmpXchgSize(&pServer->enmState, enmStateNew, enmStateOld, fRc);
195 Assert(fRc); NOREF(fRc);
196}
[1]197
[27497]198
[1]199/**
[23625]200 * Closes the a socket (client or server).
201 *
202 * @returns IPRT status code.
203 */
[24204]204static int rtTcpServerDestroySocket(RTSOCKET volatile *pSock, const char *pszMsg, bool fTryGracefulShutdown)
[23625]205{
[27497]206 RTSOCKET hSocket = rtTcpAtomicXchgSock(pSock, NIL_RTSOCKET);
207 if (hSocket != NIL_RTSOCKET)
[23625]208 {
[24204]209 if (!fTryGracefulShutdown)
[27503]210 RTSocketShutdown(hSocket, true /*fRead*/, true /*fWrite*/);
[27497]211 return rtTcpClose(hSocket, pszMsg, fTryGracefulShutdown);
[23625]212 }
213 return VINF_TCP_SERVER_NO_CLIENT;
214}
215
216
[1]217RTR3DECL(int) RTTcpServerCreate(const char *pszAddress, unsigned uPort, RTTHREADTYPE enmType, const char *pszThrdName,
218 PFNRTTCPSERVE pfnServe, void *pvUser, PPRTTCPSERVER ppServer)
219{
220 /*
[23625]221 * Validate input.
[1]222 */
[23625]223 AssertReturn(uPort > 0, VERR_INVALID_PARAMETER);
224 AssertPtrReturn(pfnServe, VERR_INVALID_POINTER);
225 AssertPtrReturn(pszThrdName, VERR_INVALID_POINTER);
226 AssertPtrReturn(ppServer, VERR_INVALID_POINTER);
[1]227
228 /*
229 * Create the server.
230 */
[23625]231 PRTTCPSERVER pServer;
[1]232 int rc = RTTcpServerCreateEx(pszAddress, uPort, &pServer);
233 if (RT_SUCCESS(rc))
234 {
235 /*
236 * Create the listener thread.
237 */
[23625]238 RTMemPoolRetain(pServer);
[1]239 pServer->enmState = RTTCPSERVERSTATE_STARTING;
240 pServer->pvUser = pvUser;
241 pServer->pfnServe = pfnServe;
242 rc = RTThreadCreate(&pServer->Thread, rtTcpServerThread, pServer, 0, enmType, /*RTTHREADFLAGS_WAITABLE*/0, pszThrdName);
243 if (RT_SUCCESS(rc))
244 {
245 /* done */
246 if (ppServer)
247 *ppServer = pServer;
[23625]248 else
249 RTMemPoolRelease(RTMEMPOOL_DEFAULT, pServer);
[1]250 return rc;
251 }
[23625]252 RTMemPoolRelease(RTMEMPOOL_DEFAULT, pServer);
[1]253
254 /*
255 * Destroy the server.
256 */
257 rtTcpServerSetState(pServer, RTTCPSERVERSTATE_CREATED, RTTCPSERVERSTATE_STARTING);
258 RTTcpServerDestroy(pServer);
259 }
260
261 return rc;
262}
263
264
265/**
266 * Server thread, loops accepting connections until it's terminated.
267 *
268 * @returns iprt status code. (ignored).
269 * @param ThreadSelf Thread handle.
270 * @param pvServer Server handle.
271 */
272static DECLCALLBACK(int) rtTcpServerThread(RTTHREAD ThreadSelf, void *pvServer)
273{
274 PRTTCPSERVER pServer = (PRTTCPSERVER)pvServer;
[23625]275 int rc;
276 if (rtTcpServerTrySetState(pServer, RTTCPSERVERSTATE_ACCEPTING, RTTCPSERVERSTATE_STARTING))
277 rc = rtTcpServerListen(pServer);
278 else
[27288]279 rc = rtTcpServerListenCleanup(pServer);
[23625]280 RTMemPoolRelease(RTMEMPOOL_DEFAULT, pServer);
[1]281 NOREF(ThreadSelf);
282 return VINF_SUCCESS;
283}
284
285
286RTR3DECL(int) RTTcpServerCreateEx(const char *pszAddress, uint32_t uPort, PPRTTCPSERVER ppServer)
287{
288 /*
[23625]289 * Validate input.
[1]290 */
[23625]291 AssertReturn(uPort > 0, VERR_INVALID_PARAMETER);
292 AssertPtrReturn(ppServer, VERR_INVALID_PARAMETER);
[1]293
294 /*
[39801]295 * Resolve the address.
[1]296 */
[39801]297 RTNETADDR LocalAddr;
298 int rc = RTSocketParseInetAddress(pszAddress, uPort, &LocalAddr);
299 if (RT_FAILURE(rc))
300 return rc;
[1]301
302 /*
303 * Setting up socket.
304 */
[27497]305 RTSOCKET WaitSock;
[96475]306 rc = rtSocketCreate(&WaitSock, AF_INET, SOCK_STREAM, IPPROTO_TCP, false /*fInheritable*/);
[27497]307 if (RT_SUCCESS(rc))
[1]308 {
309 /*
310 * Set socket options.
311 */
312 int fFlag = 1;
[27497]313 if (!rtSocketSetOpt(WaitSock, SOL_SOCKET, SO_REUSEADDR, &fFlag, sizeof(fFlag)))
[1]314 {
315 /*
[27497]316 * Bind a name to a socket and set it listening for connections.
[1]317 */
[39801]318 rc = rtSocketBind(WaitSock, &LocalAddr);
[27497]319 if (RT_SUCCESS(rc))
320 rc = rtSocketListen(WaitSock, RTTCP_SERVER_BACKLOG);
321 if (RT_SUCCESS(rc))
[1]322 {
323 /*
[27497]324 * Create the server handle.
[1]325 */
[27497]326 PRTTCPSERVER pServer = (PRTTCPSERVER)RTMemPoolAlloc(RTMEMPOOL_DEFAULT, sizeof(*pServer));
327 if (pServer)
[1]328 {
[27787]329 pServer->u32Magic = RTTCPSERVER_MAGIC;
330 pServer->enmState = RTTCPSERVERSTATE_CREATED;
331 pServer->Thread = NIL_RTTHREAD;
332 pServer->hServerSocket = WaitSock;
333 pServer->hClientSocket = NIL_RTSOCKET;
334 pServer->pfnServe = NULL;
335 pServer->pvUser = NULL;
[27497]336 *ppServer = pServer;
337 return VINF_SUCCESS;
338 }
[23613]339
[27497]340 /* bail out */
341 rc = VERR_NO_MEMORY;
[1]342 }
343 }
344 else
[27497]345 AssertMsgFailed(("rtSocketSetOpt: %Rrc\n", rc));
[24204]346 rtTcpClose(WaitSock, "RTServerCreateEx", false /*fTryGracefulShutdown*/);
[1]347 }
348
349 return rc;
350}
351
352
353RTR3DECL(int) RTTcpServerListen(PRTTCPSERVER pServer, PFNRTTCPSERVE pfnServe, void *pvUser)
354{
355 /*
[23625]356 * Validate input and retain the instance.
[1]357 */
[23625]358 AssertPtrReturn(pfnServe, VERR_INVALID_POINTER);
359 AssertPtrReturn(pServer, VERR_INVALID_HANDLE);
360 AssertReturn(pServer->u32Magic == RTTCPSERVER_MAGIC, VERR_INVALID_HANDLE);
361 AssertReturn(RTMemPoolRetain(pServer) != UINT32_MAX, VERR_INVALID_HANDLE);
362
363 int rc = VERR_INVALID_STATE;
364 if (rtTcpServerTrySetState(pServer, RTTCPSERVERSTATE_ACCEPTING, RTTCPSERVERSTATE_CREATED))
[1]365 {
366 Assert(!pServer->pfnServe);
367 Assert(!pServer->pvUser);
368 Assert(pServer->Thread == NIL_RTTHREAD);
[27787]369 Assert(pServer->hClientSocket == NIL_RTSOCKET);
[1]370
371 pServer->pfnServe = pfnServe;
372 pServer->pvUser = pvUser;
373 pServer->Thread = RTThreadSelf();
374 Assert(pServer->Thread != NIL_RTTHREAD);
[23625]375 rc = rtTcpServerListen(pServer);
[1]376 }
[23625]377 else
378 {
379 AssertMsgFailed(("enmState=%d\n", pServer->enmState));
380 rc = VERR_INVALID_STATE;
381 }
382 RTMemPoolRelease(RTMEMPOOL_DEFAULT, pServer);
383 return rc;
[1]384}
385
386
[932]387/**
[23625]388 * Internal worker common for RTTcpServerListen and the thread created by
389 * RTTcpServerCreate().
390 *
391 * The caller makes sure it has its own memory reference and releases it upon
392 * return.
[932]393 */
[1]394static int rtTcpServerListen(PRTTCPSERVER pServer)
395{
396 /*
397 * Accept connection loop.
398 */
399 for (;;)
400 {
401 /*
[27787]402 * Change state, getting an extra reference to the socket so we can
403 * allow others to close it while we're stuck in rtSocketAccept.
[1]404 */
[27787]405 RTTCPSERVERSTATE enmState = pServer->enmState;
406 RTSOCKET hServerSocket;
407 ASMAtomicXchgHandle(&pServer->hServerSocket, NIL_RTSOCKET, &hServerSocket);
408 if (hServerSocket != NIL_RTSOCKET)
409 {
410 RTSocketRetain(hServerSocket);
411 ASMAtomicWriteHandle(&pServer->hServerSocket, hServerSocket);
412 }
[1]413 if ( enmState != RTTCPSERVERSTATE_ACCEPTING
414 && enmState != RTTCPSERVERSTATE_SERVING)
[27787]415 {
416 RTSocketRelease(hServerSocket);
[27288]417 return rtTcpServerListenCleanup(pServer);
[27787]418 }
[23625]419 if (!rtTcpServerTrySetState(pServer, RTTCPSERVERSTATE_ACCEPTING, enmState))
[27787]420 {
421 RTSocketRelease(hServerSocket);
[1]422 continue;
[27787]423 }
[1]424
425 /*
426 * Accept connection.
427 */
[26252]428 struct sockaddr_in RemoteAddr;
[27497]429 size_t cbRemoteAddr = sizeof(RemoteAddr);
[27787]430 RTSOCKET hClientSocket;
[26252]431 RT_ZERO(RemoteAddr);
[27787]432 int rc = rtSocketAccept(hServerSocket, &hClientSocket, (struct sockaddr *)&RemoteAddr, &cbRemoteAddr);
433 RTSocketRelease(hServerSocket);
[27497]434 if (RT_FAILURE(rc))
[1]435 {
436 /* These are typical for what can happen during destruction. */
[27497]437 if ( rc == VERR_INVALID_HANDLE
438 || rc == VERR_INVALID_PARAMETER
439 || rc == VERR_NET_NOT_SOCKET)
[27288]440 return rtTcpServerListenCleanup(pServer);
[1]441 continue;
442 }
[27787]443 RTSocketSetInheritance(hClientSocket, false /*fInheritable*/);
[1]444
445 /*
446 * Run a pfnServe callback.
447 */
[23625]448 if (!rtTcpServerTrySetState(pServer, RTTCPSERVERSTATE_SERVING, RTTCPSERVERSTATE_ACCEPTING))
449 {
[27787]450 rtTcpClose(hClientSocket, "rtTcpServerListen", true /*fTryGracefulShutdown*/);
[27288]451 return rtTcpServerListenCleanup(pServer);
[23625]452 }
[27787]453 RTSocketRetain(hClientSocket);
454 rtTcpAtomicXchgSock(&pServer->hClientSocket, hClientSocket);
455 rc = pServer->pfnServe(hClientSocket, pServer->pvUser);
456 rtTcpServerDestroySocket(&pServer->hClientSocket, "Listener: client (secondary)", true /*fTryGracefulShutdown*/);
457 RTSocketRelease(hClientSocket);
[1]458
459 /*
460 * Stop the server?
461 */
462 if (rc == VERR_TCP_SERVER_STOP)
463 {
[23625]464 if (rtTcpServerTrySetState(pServer, RTTCPSERVERSTATE_STOPPING, RTTCPSERVERSTATE_SERVING))
[1]465 {
466 /*
467 * Reset the server socket and change the state to stopped. After that state change
468 * we cannot safely access the handle so we'll have to return here.
469 */
[27787]470 hServerSocket = rtTcpAtomicXchgSock(&pServer->hServerSocket, NIL_RTSOCKET);
[1]471 rtTcpServerSetState(pServer, RTTCPSERVERSTATE_STOPPED, RTTCPSERVERSTATE_STOPPING);
[27787]472 rtTcpClose(hServerSocket, "Listener: server stopped", false /*fTryGracefulShutdown*/);
[1]473 }
[23625]474 else
[27288]475 rtTcpServerListenCleanup(pServer); /* ignore rc */
[23625]476 return rc;
[1]477 }
478 }
479}
480
481
482/**
483 * Clean up after listener.
484 */
[27288]485static int rtTcpServerListenCleanup(PRTTCPSERVER pServer)
[1]486{
487 /*
[23625]488 * Close the server socket, the client one shouldn't be set.
[1]489 */
[27787]490 rtTcpServerDestroySocket(&pServer->hServerSocket, "ListenCleanup", false /*fTryGracefulShutdown*/);
491 Assert(pServer->hClientSocket == NIL_RTSOCKET);
[23625]492
493 /*
494 * Figure the return code and make sure the state is OK.
495 */
496 RTTCPSERVERSTATE enmState = pServer->enmState;
497 switch (enmState)
[1]498 {
[23625]499 case RTTCPSERVERSTATE_STOPPING:
500 case RTTCPSERVERSTATE_STOPPED:
501 return VERR_TCP_SERVER_SHUTDOWN;
[1]502
[23625]503 case RTTCPSERVERSTATE_ACCEPTING:
504 rtTcpServerTrySetState(pServer, RTTCPSERVERSTATE_STOPPED, enmState);
505 return VERR_TCP_SERVER_DESTROYED;
[1]506
[23625]507 case RTTCPSERVERSTATE_DESTROYING:
508 return VERR_TCP_SERVER_DESTROYED;
509
510 case RTTCPSERVERSTATE_STARTING:
511 case RTTCPSERVERSTATE_SERVING:
512 default:
513 AssertMsgFailedReturn(("pServer=%p enmState=%d\n", pServer, enmState), VERR_INTERNAL_ERROR_4);
[1]514 }
515}
516
517
[27787]518RTR3DECL(int) RTTcpServerListen2(PRTTCPSERVER pServer, PRTSOCKET phClientSocket)
[26683]519{
520 /*
521 * Validate input and retain the instance.
522 */
[27787]523 AssertPtrReturn(phClientSocket, VERR_INVALID_HANDLE);
524 *phClientSocket = NIL_RTSOCKET;
[26683]525 AssertReturn(pServer->u32Magic == RTTCPSERVER_MAGIC, VERR_INVALID_HANDLE);
526 AssertReturn(RTMemPoolRetain(pServer) != UINT32_MAX, VERR_INVALID_HANDLE);
527
528 int rc = VERR_INVALID_STATE;
529 for (;;)
530 {
531 /*
[27787]532 * Change state, getting an extra reference to the socket so we can
533 * allow others to close it while we're stuck in rtSocketAccept.
[26683]534 */
[27787]535 RTTCPSERVERSTATE enmState = pServer->enmState;
536 RTSOCKET hServerSocket;
537 ASMAtomicXchgHandle(&pServer->hServerSocket, NIL_RTSOCKET, &hServerSocket);
538 if (hServerSocket != NIL_RTSOCKET)
539 {
540 RTSocketRetain(hServerSocket);
541 ASMAtomicWriteHandle(&pServer->hServerSocket, hServerSocket);
542 }
[26683]543 if ( enmState != RTTCPSERVERSTATE_SERVING
544 && enmState != RTTCPSERVERSTATE_CREATED)
545 {
[27787]546 RTSocketRelease(hServerSocket);
547 return rtTcpServerListenCleanup(pServer);
[26683]548 }
549 if (!rtTcpServerTrySetState(pServer, RTTCPSERVERSTATE_ACCEPTING, enmState))
[27787]550 {
551 RTSocketRelease(hServerSocket);
[26683]552 continue;
[27787]553 }
[26683]554 Assert(!pServer->pfnServe);
555 Assert(!pServer->pvUser);
556 Assert(pServer->Thread == NIL_RTTHREAD);
[27787]557 Assert(pServer->hClientSocket == NIL_RTSOCKET);
[26683]558
559 /*
560 * Accept connection.
561 */
562 struct sockaddr_in RemoteAddr;
[27497]563 size_t cbRemoteAddr = sizeof(RemoteAddr);
[27787]564 RTSOCKET hClientSocket;
[26683]565 RT_ZERO(RemoteAddr);
[27787]566 rc = rtSocketAccept(hServerSocket, &hClientSocket, (struct sockaddr *)&RemoteAddr, &cbRemoteAddr);
567 RTSocketRelease(hServerSocket);
[27497]568 if (RT_FAILURE(rc))
[26683]569 {
570 if (!rtTcpServerTrySetState(pServer, RTTCPSERVERSTATE_CREATED, RTTCPSERVERSTATE_ACCEPTING))
[27288]571 rc = rtTcpServerListenCleanup(pServer);
[26683]572 if (RT_FAILURE(rc))
573 break;
574 continue;
575 }
[27787]576 RTSocketSetInheritance(hClientSocket, false /*fInheritable*/);
[26683]577
578 /*
579 * Chance to the 'serving' state and return the socket.
580 */
581 if (rtTcpServerTrySetState(pServer, RTTCPSERVERSTATE_SERVING, RTTCPSERVERSTATE_ACCEPTING))
582 {
[27787]583 *phClientSocket = hClientSocket;
[26683]584 rc = VINF_SUCCESS;
585 }
586 else
587 {
[27787]588 rtTcpClose(hClientSocket, "RTTcpServerListen2", true /*fTryGracefulShutdown*/);
[27288]589 rc = rtTcpServerListenCleanup(pServer);
[26683]590 }
591 break;
592 }
593
594 RTMemPoolRelease(RTMEMPOOL_DEFAULT, pServer);
595 return rc;
596}
597
598
[932]599RTR3DECL(int) RTTcpServerDisconnectClient(PRTTCPSERVER pServer)
600{
601 /*
[23625]602 * Validate input and retain the instance.
[932]603 */
[23625]604 AssertPtrReturn(pServer, VERR_INVALID_HANDLE);
605 AssertReturn(pServer->u32Magic == RTTCPSERVER_MAGIC, VERR_INVALID_HANDLE);
606 AssertReturn(RTMemPoolRetain(pServer) != UINT32_MAX, VERR_INVALID_HANDLE);
607
[27787]608 int rc = rtTcpServerDestroySocket(&pServer->hClientSocket, "DisconnectClient: client", true /*fTryGracefulShutdown*/);
[23625]609
610 RTMemPoolRelease(RTMEMPOOL_DEFAULT, pServer);
611 return rc;
612}
613
614
[27787]615RTR3DECL(int) RTTcpServerDisconnectClient2(RTSOCKET hClientSocket)
616{
617 return rtTcpClose(hClientSocket, "RTTcpServerDisconnectClient2", true /*fTryGracefulShutdown*/);
618}
619
620
[23625]621RTR3DECL(int) RTTcpServerShutdown(PRTTCPSERVER pServer)
622{
623 /*
624 * Validate input and retain the instance.
625 */
626 AssertPtrReturn(pServer, VERR_INVALID_HANDLE);
627 AssertReturn(pServer->u32Magic == RTTCPSERVER_MAGIC, VERR_INVALID_HANDLE);
628 AssertReturn(RTMemPoolRetain(pServer) != UINT32_MAX, VERR_INVALID_HANDLE);
629
630 /*
631 * Try change the state to stopping, then replace and destroy the server socket.
632 */
633 for (;;)
[932]634 {
[23625]635 RTTCPSERVERSTATE enmState = pServer->enmState;
636 if ( enmState != RTTCPSERVERSTATE_ACCEPTING
637 && enmState != RTTCPSERVERSTATE_SERVING)
638 {
639 RTMemPoolRelease(RTMEMPOOL_DEFAULT, pServer);
640 switch (enmState)
641 {
642 case RTTCPSERVERSTATE_CREATED:
643 case RTTCPSERVERSTATE_STARTING:
644 default:
645 AssertMsgFailed(("%d\n", enmState));
646 return VERR_INVALID_STATE;
647
648 case RTTCPSERVERSTATE_STOPPING:
649 case RTTCPSERVERSTATE_STOPPED:
650 return VINF_SUCCESS;
651
652 case RTTCPSERVERSTATE_DESTROYING:
653 return VERR_TCP_SERVER_DESTROYED;
654 }
655 }
656 if (rtTcpServerTrySetState(pServer, RTTCPSERVERSTATE_STOPPING, enmState))
657 {
[27787]658 rtTcpServerDestroySocket(&pServer->hServerSocket, "RTTcpServerShutdown", false /*fTryGracefulShutdown*/);
[23625]659 rtTcpServerSetState(pServer, RTTCPSERVERSTATE_STOPPED, RTTCPSERVERSTATE_STOPPING);
660
661 RTMemPoolRelease(RTMEMPOOL_DEFAULT, pServer);
662 return VINF_SUCCESS;
663 }
[932]664 }
665}
666
667
[1]668RTR3DECL(int) RTTcpServerDestroy(PRTTCPSERVER pServer)
669{
670 /*
[23625]671 * Validate input and retain the instance.
[1]672 */
[23625]673 AssertPtrReturn(pServer, VERR_INVALID_HANDLE);
674 AssertReturn(pServer->u32Magic == RTTCPSERVER_MAGIC, VERR_INVALID_HANDLE);
675 AssertReturn(RTMemPoolRetain(pServer) != UINT32_MAX, VERR_INVALID_HANDLE); /* paranoia */
[1]676
677 /*
[23625]678 * Move the state along so the listener can figure out what's going on.
[1]679 */
[23625]680 for (;;)
[1]681 {
[23625]682 bool fDestroyable;
[1]683 RTTCPSERVERSTATE enmState = pServer->enmState;
684 switch (enmState)
685 {
686 case RTTCPSERVERSTATE_STARTING:
687 case RTTCPSERVERSTATE_ACCEPTING:
688 case RTTCPSERVERSTATE_SERVING:
[23625]689 case RTTCPSERVERSTATE_CREATED:
690 case RTTCPSERVERSTATE_STOPPED:
691 fDestroyable = rtTcpServerTrySetState(pServer, RTTCPSERVERSTATE_DESTROYING, enmState);
[1]692 break;
693
[23625]694 /* destroyable states */
[1]695 case RTTCPSERVERSTATE_STOPPING:
[23625]696 fDestroyable = true;
[1]697 break;
698
699 /*
[23625]700 * Everything else means user or internal misbehavior.
[1]701 */
702 default:
703 AssertMsgFailed(("pServer=%p enmState=%d\n", pServer, enmState));
[23625]704 RTMemPoolRelease(RTMEMPOOL_DEFAULT, pServer);
[1]705 return VERR_INTERNAL_ERROR;
706 }
[23625]707 if (fDestroyable)
708 break;
[1]709 }
710
[23625]711 /*
712 * Destroy it.
713 */
714 ASMAtomicWriteU32(&pServer->u32Magic, ~RTTCPSERVER_MAGIC);
[27787]715 rtTcpServerDestroySocket(&pServer->hServerSocket, "Destroyer: server", false /*fTryGracefulShutdown*/);
716 rtTcpServerDestroySocket(&pServer->hClientSocket, "Destroyer: client", true /*fTryGracefulShutdown*/);
[1]717
[23625]718 /*
719 * Release it.
720 */
721 RTMemPoolRelease(RTMEMPOOL_DEFAULT, pServer);
722 RTMemPoolRelease(RTMEMPOOL_DEFAULT, pServer);
723 return VINF_SUCCESS;
[1]724}
725
726
727RTR3DECL(int) RTTcpClientConnect(const char *pszAddress, uint32_t uPort, PRTSOCKET pSock)
728{
[53536]729 return RTTcpClientConnectEx(pszAddress, uPort, pSock, RT_SOCKETCONNECT_DEFAULT_WAIT, NULL);
[45948]730}
731
732
733RTR3DECL(int) RTTcpClientConnectEx(const char *pszAddress, uint32_t uPort, PRTSOCKET pSock,
[53536]734 RTMSINTERVAL cMillies, PRTTCPCLIENTCONNECTCANCEL volatile *ppCancelCookie)
[45948]735{
[1]736 /*
[23625]737 * Validate input.
[1]738 */
[23625]739 AssertReturn(uPort > 0, VERR_INVALID_PARAMETER);
740 AssertPtrReturn(pszAddress, VERR_INVALID_POINTER);
[45948]741 AssertPtrNullReturn(ppCancelCookie, VERR_INVALID_POINTER);
[1]742
743 /*
744 * Resolve the address.
745 */
[39801]746 RTNETADDR Addr;
747 int rc = RTSocketParseInetAddress(pszAddress, uPort, &Addr);
748 if (RT_FAILURE(rc))
749 return rc;
[1]750
751 /*
752 * Create the socket and connect.
753 */
[27497]754 RTSOCKET Sock;
[96475]755 rc = rtSocketCreate(&Sock, PF_INET, SOCK_STREAM, 0, false /*fInheritable*/);
[27497]756 if (RT_SUCCESS(rc))
[1]757 {
[45948]758 if (!ppCancelCookie)
[53536]759 rc = rtSocketConnect(Sock, &Addr, cMillies);
[45948]760 else
761 {
762 RTSocketRetain(Sock);
763 if (ASMAtomicCmpXchgPtr(ppCancelCookie, (PRTTCPCLIENTCONNECTCANCEL)Sock, NULL))
764 {
[53536]765 rc = rtSocketConnect(Sock, &Addr, cMillies);
[45948]766 if (ASMAtomicCmpXchgPtr(ppCancelCookie, NULL, (PRTTCPCLIENTCONNECTCANCEL)Sock))
767 RTSocketRelease(Sock);
768 else
769 rc = VERR_CANCELLED;
770 }
771 else
772 {
773 RTSocketRelease(Sock);
774 rc = VERR_CANCELLED;
775 }
776 }
[27497]777 if (RT_SUCCESS(rc))
[1]778 {
779 *pSock = Sock;
780 return VINF_SUCCESS;
781 }
[27497]782
[24204]783 rtTcpClose(Sock, "RTTcpClientConnect", false /*fTryGracefulShutdown*/);
[1]784 }
[45948]785 if (ppCancelCookie)
786 *ppCancelCookie = NULL;
[1]787 return rc;
788}
789
790
[45948]791RTR3DECL(int) RTTcpClientCancelConnect(PRTTCPCLIENTCONNECTCANCEL volatile *ppCancelCookie)
792{
793 AssertPtrReturn(ppCancelCookie, VERR_INVALID_POINTER);
794
[79413]795 RTSOCKET const hSockCancelled = (RTSOCKET)(uintptr_t)0xdead9999;
796
[45948]797 AssertCompile(NIL_RTSOCKET == NULL);
[79413]798 RTSOCKET hSock = (RTSOCKET)ASMAtomicXchgPtr((void * volatile *)ppCancelCookie, hSockCancelled);
799 if (hSock != NIL_RTSOCKET && hSock != hSockCancelled)
[45948]800 {
801 int rc = rtTcpClose(hSock, "RTTcpClientCancelConnect", false /*fTryGracefulShutdown*/);
802 AssertRCReturn(rc, rc);
803 }
804
805 return VINF_SUCCESS;
806}
807
808
[1]809RTR3DECL(int) RTTcpClientClose(RTSOCKET Sock)
810{
[24204]811 return rtTcpClose(Sock, "RTTcpClientClose", true /*fTryGracefulShutdown*/);
[1]812}
813
814
[32818]815RTR3DECL(int) RTTcpClientCloseEx(RTSOCKET Sock, bool fGracefulShutdown)
816{
817 return rtTcpClose(Sock, "RTTcpClientCloseEx", fGracefulShutdown);
818}
819
820
[32810]821#ifdef FIX_FOR_3_2
[1]822/**
[32810]823 * Changes the blocking mode of the socket.
824 *
825 * @returns 0 on success, -1 on failure.
826 * @param hSocket The socket to work on.
827 * @param fBlocking The desired mode of operation.
828 */
829static int rtTcpSetBlockingMode(RTHCUINTPTR hSocket, bool fBlocking)
830{
831 int rc = VINF_SUCCESS;
832#ifdef RT_OS_WINDOWS
833 u_long uBlocking = fBlocking ? 0 : 1;
834 if (ioctlsocket(hSocket, FIONBIO, &uBlocking))
835 return -1;
836
837#else
838 int fFlags = fcntl(hSocket, F_GETFL, 0);
839 if (fFlags == -1)
840 return -1;
841
842 if (fBlocking)
843 fFlags &= ~O_NONBLOCK;
844 else
845 fFlags |= O_NONBLOCK;
846 if (fcntl(hSocket, F_SETFL, fFlags) == -1)
847 return -1;
848#endif
849
850 return 0;
851}
852#endif
853
854
855/**
[1]856 * Internal close function which does all the proper bitching.
857 */
[24204]858static int rtTcpClose(RTSOCKET Sock, const char *pszMsg, bool fTryGracefulShutdown)
[1]859{
[39083]860 NOREF(pszMsg); /** @todo drop this parameter? */
[24204]861
[1]862 /* ignore nil handles. */
863 if (Sock == NIL_RTSOCKET)
864 return VINF_SUCCESS;
865
866 /*
[24204]867 * Try to gracefully shut it down.
868 */
[39083]869 int rc;
[24204]870 if (fTryGracefulShutdown)
871 {
[27503]872 rc = RTSocketShutdown(Sock, false /*fRead*/, true /*fWrite*/);
[32810]873#ifdef FIX_FOR_3_2
874 RTHCUINTPTR hNative = RTSocketToNative(Sock);
875 if (RT_SUCCESS(rc) && rtTcpSetBlockingMode(hNative, false /*fBlocking*/) == 0)
876#else
[27497]877 if (RT_SUCCESS(rc))
[32810]878#endif
[24204]879 {
[32810]880
[32801]881 size_t cbReceived = 0;
882 uint64_t u64Start = RTTimeMilliTS();
883 while ( cbReceived < _1G
884 && RTTimeMilliTS() - u64Start < 30000)
[24204]885 {
[32810]886#ifdef FIX_FOR_3_2
887 fd_set FdSetR;
888 FD_ZERO(&FdSetR);
889 FD_SET(hNative, &FdSetR);
890
891 fd_set FdSetE;
892 FD_ZERO(&FdSetE);
893 FD_SET(hNative, &FdSetE);
894
895 struct timeval TvTimeout;
896 TvTimeout.tv_sec = 1;
897 TvTimeout.tv_usec = 0;
898 rc = select(hNative + 1, &FdSetR, NULL, &FdSetE, &TvTimeout);
899 if (rc == 0)
900 continue;
901 if (rc < 0)
902 break;
903 if (FD_ISSET(hNative, &FdSetE))
904 break;
905#else
[32801]906 uint32_t fEvents;
907 rc = RTSocketSelectOneEx(Sock, RTSOCKET_EVT_READ | RTSOCKET_EVT_ERROR, &fEvents, 1000);
[24204]908 if (rc == VERR_TIMEOUT)
[32801]909 continue;
910 if (RT_FAILURE(rc))
[24204]911 break;
[32801]912 if (fEvents & RTSOCKET_EVT_ERROR)
913 break;
[32810]914#endif
[32801]915
916 char abBitBucket[16*_1K];
[32810]917#ifdef FIX_FOR_3_2
[32830]918 ssize_t cbRead = recv(hNative, &abBitBucket[0], sizeof(abBitBucket), MSG_NOSIGNAL);
919 if (cbRead == 0)
[32810]920 break; /* orderly shutdown in progress */
[32830]921 if (cbRead < 0 && errno != EAGAIN)
[32810]922 break; /* some kind of error, never mind which... */
923#else
[32830]924 size_t cbRead;
[32801]925 rc = RTSocketReadNB(Sock, &abBitBucket[0], sizeof(abBitBucket), &cbRead);
926 if (RT_FAILURE(rc))
927 break; /* some kind of error, never mind which... */
928 if (rc != VINF_TRY_AGAIN && !cbRead)
929 break; /* orderly shutdown in progress */
[32810]930#endif
[32801]931
932 cbReceived += cbRead;
933 }
[24204]934 }
935 }
936
937 /*
[27787]938 * Close the socket handle (drops our reference to it).
[1]939 */
[27787]940 return RTSocketClose(Sock);
[27497]941}
942
943
[70482]944RTR3DECL(int) RTTcpCreatePair(PRTSOCKET phServer, PRTSOCKET phClient, uint32_t fFlags)
945{
946 /*
947 * Validate input.
948 */
949 AssertPtrReturn(phServer, VERR_INVALID_PARAMETER);
950 AssertPtrReturn(phClient, VERR_INVALID_PARAMETER);
951 AssertReturn(!fFlags, VERR_INVALID_PARAMETER);
952
953 /*
954 * Do the job.
955 */
956 return rtSocketCreateTcpPair(phServer, phClient);
957}
958
959
[27497]960RTR3DECL(int) RTTcpRead(RTSOCKET Sock, void *pvBuffer, size_t cbBuffer, size_t *pcbRead)
961{
[27503]962 return RTSocketRead(Sock, pvBuffer, cbBuffer, pcbRead);
[27497]963}
964
965
966RTR3DECL(int) RTTcpWrite(RTSOCKET Sock, const void *pvBuffer, size_t cbBuffer)
967{
[27503]968 return RTSocketWrite(Sock, pvBuffer, cbBuffer);
[27497]969}
970
971
972RTR3DECL(int) RTTcpFlush(RTSOCKET Sock)
973{
974 int fFlag = 1;
975 int rc = rtSocketSetOpt(Sock, IPPROTO_TCP, TCP_NODELAY, &fFlag, sizeof(fFlag));
976 if (RT_SUCCESS(rc))
977 {
978 fFlag = 0;
979 rc = rtSocketSetOpt(Sock, IPPROTO_TCP, TCP_NODELAY, &fFlag, sizeof(fFlag));
980 }
[1]981 return rc;
982}
983
[27497]984
[27959]985RTR3DECL(int) RTTcpSetSendCoalescing(RTSOCKET Sock, bool fEnable)
986{
987 int fFlag = fEnable ? 0 : 1;
988 return rtSocketSetOpt(Sock, IPPROTO_TCP, TCP_NODELAY, &fFlag, sizeof(fFlag));
989}
990
991
[78821]992RTR3DECL(int) RTTcpSetBufferSize(RTSOCKET hSocket, uint32_t cbSize)
993{
994 int cbIntSize = (int)cbSize;
995 AssertReturn(cbIntSize >= 0, VERR_OUT_OF_RANGE);
996 int rc = rtSocketSetOpt(hSocket, SOL_SOCKET, SO_SNDBUF, &cbIntSize, sizeof(cbIntSize));
997 if (RT_SUCCESS(rc))
998 rc = rtSocketSetOpt(hSocket, SOL_SOCKET, SO_RCVBUF, &cbIntSize, sizeof(cbIntSize));
999 return rc;
1000}
1001
1002
[100171]1003RTR3DECL(int) RTTcpSetKeepAlive(RTSOCKET hSocket, bool fEnable, uint32_t cSecsIdle,
1004 uint32_t cSecsInterval, uint32_t cFailedPktsBeforeClose)
1005{
1006#if !defined(RT_OS_WINDOWS)
1007 int fFlag = fEnable ? 1 : 0;
1008 int rc = rtSocketSetOpt(hSocket, SOL_SOCKET, SO_KEEPALIVE, &fFlag, sizeof(fFlag));
1009 if (RT_FAILURE(rc))
1010 return rc;
1011
[100172]1012# if (defined(TCP_KEEPIDLE) || defined(TCP_KEEPALIVE)) && defined(TCP_KEEPINTVL) && defined(TCP_KEEPCNT)
[100171]1013 rc = VINF_SUCCESS;
1014
1015 /* time in seconds that the connection must be idle before sending keep-alive probes */
1016 if (cSecsIdle)
1017 {
1018# if defined(TCP_KEEPALIVE) && !defined(TCP_KEEPIDLE) /* macOS */
1019# define TCP_KEEPIDLE TCP_KEEPALIVE
1020# endif
1021 rc = rtSocketSetOpt(hSocket, IPPROTO_TCP, TCP_KEEPIDLE, &cSecsIdle, sizeof(cSecsIdle));
1022 if (RT_FAILURE(rc))
1023 return rc;
1024 }
1025
1026 /* time in seconds between each keep-alive probe */
1027 if (cSecsInterval)
1028 {
1029 rc = rtSocketSetOpt(hSocket, IPPROTO_TCP, TCP_KEEPINTVL, &cSecsInterval, sizeof(cSecsInterval));
1030 if (RT_FAILURE(rc))
1031 return rc;
1032 }
1033
1034 /* count of keep-alive probes to send which don't receive a response before closing connection */
1035 if (cFailedPktsBeforeClose)
1036 {
1037 rc = rtSocketSetOpt(hSocket, IPPROTO_TCP, TCP_KEEPCNT, &cFailedPktsBeforeClose, sizeof(cFailedPktsBeforeClose));
1038 if (RT_FAILURE(rc))
1039 return rc;
1040 }
1041
1042 return rc;
1043# else
1044 return VERR_NOT_SUPPORTED;
1045# endif
1046#else
1047 NOREF(cFailedPktsBeforeClose);
1048 return rtSocketSetKeepAlive(hSocket, fEnable, cSecsIdle, cSecsInterval);
1049#endif
1050}
1051
1052
[27497]1053RTR3DECL(int) RTTcpSelectOne(RTSOCKET Sock, RTMSINTERVAL cMillies)
1054{
[27503]1055 return RTSocketSelectOne(Sock, cMillies);
[27497]1056}
1057
1058
[32276]1059RTR3DECL(int) RTTcpSelectOneEx(RTSOCKET Sock, uint32_t fEvents, uint32_t *pfEvents,
1060 RTMSINTERVAL cMillies)
1061{
1062 return RTSocketSelectOneEx(Sock, fEvents, pfEvents, cMillies);
1063}
1064
1065
[27497]1066RTR3DECL(int) RTTcpGetLocalAddress(RTSOCKET Sock, PRTNETADDR pAddr)
1067{
[27503]1068 return RTSocketGetLocalAddress(Sock, pAddr);
[27497]1069}
1070
1071
1072RTR3DECL(int) RTTcpGetPeerAddress(RTSOCKET Sock, PRTNETADDR pAddr)
1073{
[27503]1074 return RTSocketGetPeerAddress(Sock, pAddr);
[27497]1075}
1076
[30270]1077
1078RTR3DECL(int) RTTcpSgWrite(RTSOCKET Sock, PCRTSGBUF pSgBuf)
1079{
1080 return RTSocketSgWrite(Sock, pSgBuf);
1081}
1082
[30468]1083
1084RTR3DECL(int) RTTcpSgWriteL(RTSOCKET hSocket, size_t cSegs, ...)
1085{
1086 va_list va;
1087 va_start(va, cSegs);
1088 int rc = RTSocketSgWriteLV(hSocket, cSegs, va);
1089 va_end(va);
1090 return rc;
1091}
1092
1093
1094RTR3DECL(int) RTTcpSgWriteLV(RTSOCKET hSocket, size_t cSegs, va_list va)
1095{
1096 return RTSocketSgWriteLV(hSocket, cSegs, va);
1097}
1098
[31103]1099
1100RTR3DECL(int) RTTcpReadNB(RTSOCKET Sock, void *pvBuffer, size_t cbBuffer, size_t *pcbRead)
1101{
1102 return RTSocketReadNB(Sock, pvBuffer, cbBuffer, pcbRead);
1103}
1104
1105
1106RTR3DECL(int) RTTcpWriteNB(RTSOCKET Sock, const void *pvBuffer, size_t cbBuffer, size_t *pcbWritten)
1107{
1108 return RTSocketWriteNB(Sock, pvBuffer, cbBuffer, pcbWritten);
1109}
1110
1111
1112RTR3DECL(int) RTTcpSgWriteNB(RTSOCKET Sock, PCRTSGBUF pSgBuf, size_t *pcbWritten)
1113{
1114 return RTSocketSgWriteNB(Sock, pSgBuf, pcbWritten);
1115}
1116
1117
1118RTR3DECL(int) RTTcpSgWriteLNB(RTSOCKET hSocket, size_t cSegs, size_t *pcbWritten, ...)
1119{
1120 va_list va;
1121 va_start(va, pcbWritten);
1122 int rc = RTSocketSgWriteLVNB(hSocket, cSegs, pcbWritten, va);
1123 va_end(va);
1124 return rc;
1125}
1126
1127
1128RTR3DECL(int) RTTcpSgWriteLVNB(RTSOCKET hSocket, size_t cSegs, size_t *pcbWritten, va_list va)
1129{
1130 return RTSocketSgWriteLVNB(hSocket, cSegs, pcbWritten, va);
1131}
1132
Note: See TracBrowser for help on using the repository browser.

© 2023 Oracle
ContactPrivacy policyTerms of Use