VirtualBox

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

Last change on this file since 103914 was 100172, checked in by vboxsync, 17 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
Line 
1/* $Id: tcp.cpp 100172 2023-06-13 21:58:48Z vboxsync $ */
2/** @file
3 * IPRT - TCP/IP.
4 */
5
6/*
7 * Copyright (C) 2006-2023 Oracle and/or its affiliates.
8 *
9 * This file is part of VirtualBox base platform packages, as
10 * available from https://www.virtualbox.org.
11 *
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 *
25 * The contents of this file may alternatively be used under the terms
26 * of the Common Development and Distribution License Version 1.0
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
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.
33 *
34 * SPDX-License-Identifier: GPL-3.0-only OR CDDL-1.0
35 */
36
37
38/*********************************************************************************************************************************
39* Header Files *
40*********************************************************************************************************************************/
41#ifdef RT_OS_WINDOWS
42# include <iprt/win/winsock2.h>
43#else
44# include <sys/types.h>
45# include <sys/socket.h>
46# include <errno.h>
47# include <netinet/in.h>
48# include <netinet/tcp.h>
49# include <arpa/inet.h>
50# include <netdb.h>
51# ifdef FIX_FOR_3_2
52# include <fcntl.h>
53# endif
54#endif
55#include <limits.h>
56
57#include "internal/iprt.h"
58#include <iprt/tcp.h>
59
60#include <iprt/asm.h>
61#include <iprt/assert.h>
62#include <iprt/err.h>
63#include <iprt/log.h>
64#include <iprt/mempool.h>
65#include <iprt/mem.h>
66#include <iprt/string.h>
67#include <iprt/socket.h>
68#include <iprt/thread.h>
69#include <iprt/time.h>
70
71#include "internal/magics.h"
72#include "internal/socket.h"
73
74
75/*********************************************************************************************************************************
76* Defined Constants And Macros *
77*********************************************************************************************************************************/
78/* non-standard linux stuff (it seems). */
79#ifndef MSG_NOSIGNAL
80# define MSG_NOSIGNAL 0
81#endif
82#ifndef SHUT_RDWR
83# ifdef SD_BOTH
84# define SHUT_RDWR SD_BOTH
85# else
86# define SHUT_RDWR 2
87# endif
88#endif
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
96
97/* fixup backlevel OSes. */
98#if defined(RT_OS_OS2) || defined(RT_OS_WINDOWS)
99# define socklen_t int
100#endif
101
102/** How many pending connection. */
103#define RTTCP_SERVER_BACKLOG 10
104
105
106/*********************************************************************************************************************************
107* Structures and Typedefs *
108*********************************************************************************************************************************/
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. */
129 RTTCPSERVERSTATE_DESTROYING
130} RTTCPSERVERSTATE;
131
132/*
133 * Internal representation of the TCP Server handle.
134 */
135typedef struct RTTCPSERVER
136{
137 /** The magic value (RTTCPSERVER_MAGIC). */
138 uint32_t volatile u32Magic;
139 /** The server state. */
140 RTTCPSERVERSTATE volatile enmState;
141 /** The server thread. */
142 RTTHREAD Thread;
143 /** The server socket. */
144 RTSOCKET volatile hServerSocket;
145 /** The socket to the client currently being serviced.
146 * This is NIL_RTSOCKET when no client is serviced. */
147 RTSOCKET volatile hClientSocket;
148 /** The connection function. */
149 PFNRTTCPSERVE pfnServe;
150 /** Argument to pfnServer. */
151 void *pvUser;
152} RTTCPSERVER;
153
154
155/*********************************************************************************************************************************
156* Internal Functions *
157*********************************************************************************************************************************/
158static DECLCALLBACK(int) rtTcpServerThread(RTTHREAD ThreadSelf, void *pvServer);
159static int rtTcpServerListen(PRTTCPSERVER pServer);
160static int rtTcpServerListenCleanup(PRTTCPSERVER pServer);
161static int rtTcpClose(RTSOCKET Sock, const char *pszMsg, bool fTryGracefulShutdown);
162
163
164/**
165 * Atomicly updates a socket variable.
166 * @returns The old handle value.
167 * @param phSock The socket handle variable to update.
168 * @param hNew The new socket handle value.
169 */
170DECLINLINE(RTSOCKET) rtTcpAtomicXchgSock(RTSOCKET volatile *phSock, const RTSOCKET hNew)
171{
172 RTSOCKET hRet;
173 ASMAtomicXchgHandle(phSock, hNew, &hRet);
174 return hRet;
175}
176
177
178/**
179 * Tries to change the TCP server state.
180 */
181DECLINLINE(bool) rtTcpServerTrySetState(PRTTCPSERVER pServer, RTTCPSERVERSTATE enmStateNew, RTTCPSERVERSTATE enmStateOld)
182{
183 bool fRc;
184 ASMAtomicCmpXchgSize(&pServer->enmState, enmStateNew, enmStateOld, fRc);
185 return fRc;
186}
187
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}
197
198
199/**
200 * Closes the a socket (client or server).
201 *
202 * @returns IPRT status code.
203 */
204static int rtTcpServerDestroySocket(RTSOCKET volatile *pSock, const char *pszMsg, bool fTryGracefulShutdown)
205{
206 RTSOCKET hSocket = rtTcpAtomicXchgSock(pSock, NIL_RTSOCKET);
207 if (hSocket != NIL_RTSOCKET)
208 {
209 if (!fTryGracefulShutdown)
210 RTSocketShutdown(hSocket, true /*fRead*/, true /*fWrite*/);
211 return rtTcpClose(hSocket, pszMsg, fTryGracefulShutdown);
212 }
213 return VINF_TCP_SERVER_NO_CLIENT;
214}
215
216
217RTR3DECL(int) RTTcpServerCreate(const char *pszAddress, unsigned uPort, RTTHREADTYPE enmType, const char *pszThrdName,
218 PFNRTTCPSERVE pfnServe, void *pvUser, PPRTTCPSERVER ppServer)
219{
220 /*
221 * Validate input.
222 */
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);
227
228 /*
229 * Create the server.
230 */
231 PRTTCPSERVER pServer;
232 int rc = RTTcpServerCreateEx(pszAddress, uPort, &pServer);
233 if (RT_SUCCESS(rc))
234 {
235 /*
236 * Create the listener thread.
237 */
238 RTMemPoolRetain(pServer);
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;
248 else
249 RTMemPoolRelease(RTMEMPOOL_DEFAULT, pServer);
250 return rc;
251 }
252 RTMemPoolRelease(RTMEMPOOL_DEFAULT, pServer);
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;
275 int rc;
276 if (rtTcpServerTrySetState(pServer, RTTCPSERVERSTATE_ACCEPTING, RTTCPSERVERSTATE_STARTING))
277 rc = rtTcpServerListen(pServer);
278 else
279 rc = rtTcpServerListenCleanup(pServer);
280 RTMemPoolRelease(RTMEMPOOL_DEFAULT, pServer);
281 NOREF(ThreadSelf);
282 return VINF_SUCCESS;
283}
284
285
286RTR3DECL(int) RTTcpServerCreateEx(const char *pszAddress, uint32_t uPort, PPRTTCPSERVER ppServer)
287{
288 /*
289 * Validate input.
290 */
291 AssertReturn(uPort > 0, VERR_INVALID_PARAMETER);
292 AssertPtrReturn(ppServer, VERR_INVALID_PARAMETER);
293
294 /*
295 * Resolve the address.
296 */
297 RTNETADDR LocalAddr;
298 int rc = RTSocketParseInetAddress(pszAddress, uPort, &LocalAddr);
299 if (RT_FAILURE(rc))
300 return rc;
301
302 /*
303 * Setting up socket.
304 */
305 RTSOCKET WaitSock;
306 rc = rtSocketCreate(&WaitSock, AF_INET, SOCK_STREAM, IPPROTO_TCP, false /*fInheritable*/);
307 if (RT_SUCCESS(rc))
308 {
309 /*
310 * Set socket options.
311 */
312 int fFlag = 1;
313 if (!rtSocketSetOpt(WaitSock, SOL_SOCKET, SO_REUSEADDR, &fFlag, sizeof(fFlag)))
314 {
315 /*
316 * Bind a name to a socket and set it listening for connections.
317 */
318 rc = rtSocketBind(WaitSock, &LocalAddr);
319 if (RT_SUCCESS(rc))
320 rc = rtSocketListen(WaitSock, RTTCP_SERVER_BACKLOG);
321 if (RT_SUCCESS(rc))
322 {
323 /*
324 * Create the server handle.
325 */
326 PRTTCPSERVER pServer = (PRTTCPSERVER)RTMemPoolAlloc(RTMEMPOOL_DEFAULT, sizeof(*pServer));
327 if (pServer)
328 {
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;
336 *ppServer = pServer;
337 return VINF_SUCCESS;
338 }
339
340 /* bail out */
341 rc = VERR_NO_MEMORY;
342 }
343 }
344 else
345 AssertMsgFailed(("rtSocketSetOpt: %Rrc\n", rc));
346 rtTcpClose(WaitSock, "RTServerCreateEx", false /*fTryGracefulShutdown*/);
347 }
348
349 return rc;
350}
351
352
353RTR3DECL(int) RTTcpServerListen(PRTTCPSERVER pServer, PFNRTTCPSERVE pfnServe, void *pvUser)
354{
355 /*
356 * Validate input and retain the instance.
357 */
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))
365 {
366 Assert(!pServer->pfnServe);
367 Assert(!pServer->pvUser);
368 Assert(pServer->Thread == NIL_RTTHREAD);
369 Assert(pServer->hClientSocket == NIL_RTSOCKET);
370
371 pServer->pfnServe = pfnServe;
372 pServer->pvUser = pvUser;
373 pServer->Thread = RTThreadSelf();
374 Assert(pServer->Thread != NIL_RTTHREAD);
375 rc = rtTcpServerListen(pServer);
376 }
377 else
378 {
379 AssertMsgFailed(("enmState=%d\n", pServer->enmState));
380 rc = VERR_INVALID_STATE;
381 }
382 RTMemPoolRelease(RTMEMPOOL_DEFAULT, pServer);
383 return rc;
384}
385
386
387/**
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.
393 */
394static int rtTcpServerListen(PRTTCPSERVER pServer)
395{
396 /*
397 * Accept connection loop.
398 */
399 for (;;)
400 {
401 /*
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.
404 */
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 }
413 if ( enmState != RTTCPSERVERSTATE_ACCEPTING
414 && enmState != RTTCPSERVERSTATE_SERVING)
415 {
416 RTSocketRelease(hServerSocket);
417 return rtTcpServerListenCleanup(pServer);
418 }
419 if (!rtTcpServerTrySetState(pServer, RTTCPSERVERSTATE_ACCEPTING, enmState))
420 {
421 RTSocketRelease(hServerSocket);
422 continue;
423 }
424
425 /*
426 * Accept connection.
427 */
428 struct sockaddr_in RemoteAddr;
429 size_t cbRemoteAddr = sizeof(RemoteAddr);
430 RTSOCKET hClientSocket;
431 RT_ZERO(RemoteAddr);
432 int rc = rtSocketAccept(hServerSocket, &hClientSocket, (struct sockaddr *)&RemoteAddr, &cbRemoteAddr);
433 RTSocketRelease(hServerSocket);
434 if (RT_FAILURE(rc))
435 {
436 /* These are typical for what can happen during destruction. */
437 if ( rc == VERR_INVALID_HANDLE
438 || rc == VERR_INVALID_PARAMETER
439 || rc == VERR_NET_NOT_SOCKET)
440 return rtTcpServerListenCleanup(pServer);
441 continue;
442 }
443 RTSocketSetInheritance(hClientSocket, false /*fInheritable*/);
444
445 /*
446 * Run a pfnServe callback.
447 */
448 if (!rtTcpServerTrySetState(pServer, RTTCPSERVERSTATE_SERVING, RTTCPSERVERSTATE_ACCEPTING))
449 {
450 rtTcpClose(hClientSocket, "rtTcpServerListen", true /*fTryGracefulShutdown*/);
451 return rtTcpServerListenCleanup(pServer);
452 }
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);
458
459 /*
460 * Stop the server?
461 */
462 if (rc == VERR_TCP_SERVER_STOP)
463 {
464 if (rtTcpServerTrySetState(pServer, RTTCPSERVERSTATE_STOPPING, RTTCPSERVERSTATE_SERVING))
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 */
470 hServerSocket = rtTcpAtomicXchgSock(&pServer->hServerSocket, NIL_RTSOCKET);
471 rtTcpServerSetState(pServer, RTTCPSERVERSTATE_STOPPED, RTTCPSERVERSTATE_STOPPING);
472 rtTcpClose(hServerSocket, "Listener: server stopped", false /*fTryGracefulShutdown*/);
473 }
474 else
475 rtTcpServerListenCleanup(pServer); /* ignore rc */
476 return rc;
477 }
478 }
479}
480
481
482/**
483 * Clean up after listener.
484 */
485static int rtTcpServerListenCleanup(PRTTCPSERVER pServer)
486{
487 /*
488 * Close the server socket, the client one shouldn't be set.
489 */
490 rtTcpServerDestroySocket(&pServer->hServerSocket, "ListenCleanup", false /*fTryGracefulShutdown*/);
491 Assert(pServer->hClientSocket == NIL_RTSOCKET);
492
493 /*
494 * Figure the return code and make sure the state is OK.
495 */
496 RTTCPSERVERSTATE enmState = pServer->enmState;
497 switch (enmState)
498 {
499 case RTTCPSERVERSTATE_STOPPING:
500 case RTTCPSERVERSTATE_STOPPED:
501 return VERR_TCP_SERVER_SHUTDOWN;
502
503 case RTTCPSERVERSTATE_ACCEPTING:
504 rtTcpServerTrySetState(pServer, RTTCPSERVERSTATE_STOPPED, enmState);
505 return VERR_TCP_SERVER_DESTROYED;
506
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);
514 }
515}
516
517
518RTR3DECL(int) RTTcpServerListen2(PRTTCPSERVER pServer, PRTSOCKET phClientSocket)
519{
520 /*
521 * Validate input and retain the instance.
522 */
523 AssertPtrReturn(phClientSocket, VERR_INVALID_HANDLE);
524 *phClientSocket = NIL_RTSOCKET;
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 /*
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.
534 */
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 }
543 if ( enmState != RTTCPSERVERSTATE_SERVING
544 && enmState != RTTCPSERVERSTATE_CREATED)
545 {
546 RTSocketRelease(hServerSocket);
547 return rtTcpServerListenCleanup(pServer);
548 }
549 if (!rtTcpServerTrySetState(pServer, RTTCPSERVERSTATE_ACCEPTING, enmState))
550 {
551 RTSocketRelease(hServerSocket);
552 continue;
553 }
554 Assert(!pServer->pfnServe);
555 Assert(!pServer->pvUser);
556 Assert(pServer->Thread == NIL_RTTHREAD);
557 Assert(pServer->hClientSocket == NIL_RTSOCKET);
558
559 /*
560 * Accept connection.
561 */
562 struct sockaddr_in RemoteAddr;
563 size_t cbRemoteAddr = sizeof(RemoteAddr);
564 RTSOCKET hClientSocket;
565 RT_ZERO(RemoteAddr);
566 rc = rtSocketAccept(hServerSocket, &hClientSocket, (struct sockaddr *)&RemoteAddr, &cbRemoteAddr);
567 RTSocketRelease(hServerSocket);
568 if (RT_FAILURE(rc))
569 {
570 if (!rtTcpServerTrySetState(pServer, RTTCPSERVERSTATE_CREATED, RTTCPSERVERSTATE_ACCEPTING))
571 rc = rtTcpServerListenCleanup(pServer);
572 if (RT_FAILURE(rc))
573 break;
574 continue;
575 }
576 RTSocketSetInheritance(hClientSocket, false /*fInheritable*/);
577
578 /*
579 * Chance to the 'serving' state and return the socket.
580 */
581 if (rtTcpServerTrySetState(pServer, RTTCPSERVERSTATE_SERVING, RTTCPSERVERSTATE_ACCEPTING))
582 {
583 *phClientSocket = hClientSocket;
584 rc = VINF_SUCCESS;
585 }
586 else
587 {
588 rtTcpClose(hClientSocket, "RTTcpServerListen2", true /*fTryGracefulShutdown*/);
589 rc = rtTcpServerListenCleanup(pServer);
590 }
591 break;
592 }
593
594 RTMemPoolRelease(RTMEMPOOL_DEFAULT, pServer);
595 return rc;
596}
597
598
599RTR3DECL(int) RTTcpServerDisconnectClient(PRTTCPSERVER pServer)
600{
601 /*
602 * Validate input and retain the instance.
603 */
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
608 int rc = rtTcpServerDestroySocket(&pServer->hClientSocket, "DisconnectClient: client", true /*fTryGracefulShutdown*/);
609
610 RTMemPoolRelease(RTMEMPOOL_DEFAULT, pServer);
611 return rc;
612}
613
614
615RTR3DECL(int) RTTcpServerDisconnectClient2(RTSOCKET hClientSocket)
616{
617 return rtTcpClose(hClientSocket, "RTTcpServerDisconnectClient2", true /*fTryGracefulShutdown*/);
618}
619
620
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 (;;)
634 {
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 {
658 rtTcpServerDestroySocket(&pServer->hServerSocket, "RTTcpServerShutdown", false /*fTryGracefulShutdown*/);
659 rtTcpServerSetState(pServer, RTTCPSERVERSTATE_STOPPED, RTTCPSERVERSTATE_STOPPING);
660
661 RTMemPoolRelease(RTMEMPOOL_DEFAULT, pServer);
662 return VINF_SUCCESS;
663 }
664 }
665}
666
667
668RTR3DECL(int) RTTcpServerDestroy(PRTTCPSERVER pServer)
669{
670 /*
671 * Validate input and retain the instance.
672 */
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 */
676
677 /*
678 * Move the state along so the listener can figure out what's going on.
679 */
680 for (;;)
681 {
682 bool fDestroyable;
683 RTTCPSERVERSTATE enmState = pServer->enmState;
684 switch (enmState)
685 {
686 case RTTCPSERVERSTATE_STARTING:
687 case RTTCPSERVERSTATE_ACCEPTING:
688 case RTTCPSERVERSTATE_SERVING:
689 case RTTCPSERVERSTATE_CREATED:
690 case RTTCPSERVERSTATE_STOPPED:
691 fDestroyable = rtTcpServerTrySetState(pServer, RTTCPSERVERSTATE_DESTROYING, enmState);
692 break;
693
694 /* destroyable states */
695 case RTTCPSERVERSTATE_STOPPING:
696 fDestroyable = true;
697 break;
698
699 /*
700 * Everything else means user or internal misbehavior.
701 */
702 default:
703 AssertMsgFailed(("pServer=%p enmState=%d\n", pServer, enmState));
704 RTMemPoolRelease(RTMEMPOOL_DEFAULT, pServer);
705 return VERR_INTERNAL_ERROR;
706 }
707 if (fDestroyable)
708 break;
709 }
710
711 /*
712 * Destroy it.
713 */
714 ASMAtomicWriteU32(&pServer->u32Magic, ~RTTCPSERVER_MAGIC);
715 rtTcpServerDestroySocket(&pServer->hServerSocket, "Destroyer: server", false /*fTryGracefulShutdown*/);
716 rtTcpServerDestroySocket(&pServer->hClientSocket, "Destroyer: client", true /*fTryGracefulShutdown*/);
717
718 /*
719 * Release it.
720 */
721 RTMemPoolRelease(RTMEMPOOL_DEFAULT, pServer);
722 RTMemPoolRelease(RTMEMPOOL_DEFAULT, pServer);
723 return VINF_SUCCESS;
724}
725
726
727RTR3DECL(int) RTTcpClientConnect(const char *pszAddress, uint32_t uPort, PRTSOCKET pSock)
728{
729 return RTTcpClientConnectEx(pszAddress, uPort, pSock, RT_SOCKETCONNECT_DEFAULT_WAIT, NULL);
730}
731
732
733RTR3DECL(int) RTTcpClientConnectEx(const char *pszAddress, uint32_t uPort, PRTSOCKET pSock,
734 RTMSINTERVAL cMillies, PRTTCPCLIENTCONNECTCANCEL volatile *ppCancelCookie)
735{
736 /*
737 * Validate input.
738 */
739 AssertReturn(uPort > 0, VERR_INVALID_PARAMETER);
740 AssertPtrReturn(pszAddress, VERR_INVALID_POINTER);
741 AssertPtrNullReturn(ppCancelCookie, VERR_INVALID_POINTER);
742
743 /*
744 * Resolve the address.
745 */
746 RTNETADDR Addr;
747 int rc = RTSocketParseInetAddress(pszAddress, uPort, &Addr);
748 if (RT_FAILURE(rc))
749 return rc;
750
751 /*
752 * Create the socket and connect.
753 */
754 RTSOCKET Sock;
755 rc = rtSocketCreate(&Sock, PF_INET, SOCK_STREAM, 0, false /*fInheritable*/);
756 if (RT_SUCCESS(rc))
757 {
758 if (!ppCancelCookie)
759 rc = rtSocketConnect(Sock, &Addr, cMillies);
760 else
761 {
762 RTSocketRetain(Sock);
763 if (ASMAtomicCmpXchgPtr(ppCancelCookie, (PRTTCPCLIENTCONNECTCANCEL)Sock, NULL))
764 {
765 rc = rtSocketConnect(Sock, &Addr, cMillies);
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 }
777 if (RT_SUCCESS(rc))
778 {
779 *pSock = Sock;
780 return VINF_SUCCESS;
781 }
782
783 rtTcpClose(Sock, "RTTcpClientConnect", false /*fTryGracefulShutdown*/);
784 }
785 if (ppCancelCookie)
786 *ppCancelCookie = NULL;
787 return rc;
788}
789
790
791RTR3DECL(int) RTTcpClientCancelConnect(PRTTCPCLIENTCONNECTCANCEL volatile *ppCancelCookie)
792{
793 AssertPtrReturn(ppCancelCookie, VERR_INVALID_POINTER);
794
795 RTSOCKET const hSockCancelled = (RTSOCKET)(uintptr_t)0xdead9999;
796
797 AssertCompile(NIL_RTSOCKET == NULL);
798 RTSOCKET hSock = (RTSOCKET)ASMAtomicXchgPtr((void * volatile *)ppCancelCookie, hSockCancelled);
799 if (hSock != NIL_RTSOCKET && hSock != hSockCancelled)
800 {
801 int rc = rtTcpClose(hSock, "RTTcpClientCancelConnect", false /*fTryGracefulShutdown*/);
802 AssertRCReturn(rc, rc);
803 }
804
805 return VINF_SUCCESS;
806}
807
808
809RTR3DECL(int) RTTcpClientClose(RTSOCKET Sock)
810{
811 return rtTcpClose(Sock, "RTTcpClientClose", true /*fTryGracefulShutdown*/);
812}
813
814
815RTR3DECL(int) RTTcpClientCloseEx(RTSOCKET Sock, bool fGracefulShutdown)
816{
817 return rtTcpClose(Sock, "RTTcpClientCloseEx", fGracefulShutdown);
818}
819
820
821#ifdef FIX_FOR_3_2
822/**
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/**
856 * Internal close function which does all the proper bitching.
857 */
858static int rtTcpClose(RTSOCKET Sock, const char *pszMsg, bool fTryGracefulShutdown)
859{
860 NOREF(pszMsg); /** @todo drop this parameter? */
861
862 /* ignore nil handles. */
863 if (Sock == NIL_RTSOCKET)
864 return VINF_SUCCESS;
865
866 /*
867 * Try to gracefully shut it down.
868 */
869 int rc;
870 if (fTryGracefulShutdown)
871 {
872 rc = RTSocketShutdown(Sock, false /*fRead*/, true /*fWrite*/);
873#ifdef FIX_FOR_3_2
874 RTHCUINTPTR hNative = RTSocketToNative(Sock);
875 if (RT_SUCCESS(rc) && rtTcpSetBlockingMode(hNative, false /*fBlocking*/) == 0)
876#else
877 if (RT_SUCCESS(rc))
878#endif
879 {
880
881 size_t cbReceived = 0;
882 uint64_t u64Start = RTTimeMilliTS();
883 while ( cbReceived < _1G
884 && RTTimeMilliTS() - u64Start < 30000)
885 {
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
906 uint32_t fEvents;
907 rc = RTSocketSelectOneEx(Sock, RTSOCKET_EVT_READ | RTSOCKET_EVT_ERROR, &fEvents, 1000);
908 if (rc == VERR_TIMEOUT)
909 continue;
910 if (RT_FAILURE(rc))
911 break;
912 if (fEvents & RTSOCKET_EVT_ERROR)
913 break;
914#endif
915
916 char abBitBucket[16*_1K];
917#ifdef FIX_FOR_3_2
918 ssize_t cbRead = recv(hNative, &abBitBucket[0], sizeof(abBitBucket), MSG_NOSIGNAL);
919 if (cbRead == 0)
920 break; /* orderly shutdown in progress */
921 if (cbRead < 0 && errno != EAGAIN)
922 break; /* some kind of error, never mind which... */
923#else
924 size_t cbRead;
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 */
930#endif
931
932 cbReceived += cbRead;
933 }
934 }
935 }
936
937 /*
938 * Close the socket handle (drops our reference to it).
939 */
940 return RTSocketClose(Sock);
941}
942
943
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
960RTR3DECL(int) RTTcpRead(RTSOCKET Sock, void *pvBuffer, size_t cbBuffer, size_t *pcbRead)
961{
962 return RTSocketRead(Sock, pvBuffer, cbBuffer, pcbRead);
963}
964
965
966RTR3DECL(int) RTTcpWrite(RTSOCKET Sock, const void *pvBuffer, size_t cbBuffer)
967{
968 return RTSocketWrite(Sock, pvBuffer, cbBuffer);
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 }
981 return rc;
982}
983
984
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
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
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
1012# if (defined(TCP_KEEPIDLE) || defined(TCP_KEEPALIVE)) && defined(TCP_KEEPINTVL) && defined(TCP_KEEPCNT)
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
1053RTR3DECL(int) RTTcpSelectOne(RTSOCKET Sock, RTMSINTERVAL cMillies)
1054{
1055 return RTSocketSelectOne(Sock, cMillies);
1056}
1057
1058
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
1066RTR3DECL(int) RTTcpGetLocalAddress(RTSOCKET Sock, PRTNETADDR pAddr)
1067{
1068 return RTSocketGetLocalAddress(Sock, pAddr);
1069}
1070
1071
1072RTR3DECL(int) RTTcpGetPeerAddress(RTSOCKET Sock, PRTNETADDR pAddr)
1073{
1074 return RTSocketGetPeerAddress(Sock, pAddr);
1075}
1076
1077
1078RTR3DECL(int) RTTcpSgWrite(RTSOCKET Sock, PCRTSGBUF pSgBuf)
1079{
1080 return RTSocketSgWrite(Sock, pSgBuf);
1081}
1082
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
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.

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