VirtualBox

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

Last change on this file since 98103 was 98103, checked in by vboxsync, 23 months ago

Copyright year updates by scm.

  • Property svn:eol-style set to native
  • Property svn:keywords set to Id Revision
File size: 37.0 KB
Line 
1/* $Id: tcp.cpp 98103 2023-01-17 14:15:46Z 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
217/**
218 * Create single connection at a time TCP Server in a separate thread.
219 *
220 * The thread will loop accepting connections and call pfnServe for
221 * each of the incoming connections in turn. The pfnServe function can
222 * return VERR_TCP_SERVER_STOP too terminate this loop. RTTcpServerDestroy()
223 * should be used to terminate the server.
224 *
225 * @returns iprt status code.
226 * @param pszAddress The address for creating a listening socket.
227 * If NULL or empty string the server is bound to all interfaces.
228 * @param uPort The port for creating a listening socket.
229 * @param enmType The thread type.
230 * @param pszThrdName The name of the worker thread.
231 * @param pfnServe The function which will serve a new client connection.
232 * @param pvUser User argument passed to pfnServe.
233 * @param ppServer Where to store the serverhandle.
234 */
235RTR3DECL(int) RTTcpServerCreate(const char *pszAddress, unsigned uPort, RTTHREADTYPE enmType, const char *pszThrdName,
236 PFNRTTCPSERVE pfnServe, void *pvUser, PPRTTCPSERVER ppServer)
237{
238 /*
239 * Validate input.
240 */
241 AssertReturn(uPort > 0, VERR_INVALID_PARAMETER);
242 AssertPtrReturn(pfnServe, VERR_INVALID_POINTER);
243 AssertPtrReturn(pszThrdName, VERR_INVALID_POINTER);
244 AssertPtrReturn(ppServer, VERR_INVALID_POINTER);
245
246 /*
247 * Create the server.
248 */
249 PRTTCPSERVER pServer;
250 int rc = RTTcpServerCreateEx(pszAddress, uPort, &pServer);
251 if (RT_SUCCESS(rc))
252 {
253 /*
254 * Create the listener thread.
255 */
256 RTMemPoolRetain(pServer);
257 pServer->enmState = RTTCPSERVERSTATE_STARTING;
258 pServer->pvUser = pvUser;
259 pServer->pfnServe = pfnServe;
260 rc = RTThreadCreate(&pServer->Thread, rtTcpServerThread, pServer, 0, enmType, /*RTTHREADFLAGS_WAITABLE*/0, pszThrdName);
261 if (RT_SUCCESS(rc))
262 {
263 /* done */
264 if (ppServer)
265 *ppServer = pServer;
266 else
267 RTMemPoolRelease(RTMEMPOOL_DEFAULT, pServer);
268 return rc;
269 }
270 RTMemPoolRelease(RTMEMPOOL_DEFAULT, pServer);
271
272 /*
273 * Destroy the server.
274 */
275 rtTcpServerSetState(pServer, RTTCPSERVERSTATE_CREATED, RTTCPSERVERSTATE_STARTING);
276 RTTcpServerDestroy(pServer);
277 }
278
279 return rc;
280}
281
282
283/**
284 * Server thread, loops accepting connections until it's terminated.
285 *
286 * @returns iprt status code. (ignored).
287 * @param ThreadSelf Thread handle.
288 * @param pvServer Server handle.
289 */
290static DECLCALLBACK(int) rtTcpServerThread(RTTHREAD ThreadSelf, void *pvServer)
291{
292 PRTTCPSERVER pServer = (PRTTCPSERVER)pvServer;
293 int rc;
294 if (rtTcpServerTrySetState(pServer, RTTCPSERVERSTATE_ACCEPTING, RTTCPSERVERSTATE_STARTING))
295 rc = rtTcpServerListen(pServer);
296 else
297 rc = rtTcpServerListenCleanup(pServer);
298 RTMemPoolRelease(RTMEMPOOL_DEFAULT, pServer);
299 NOREF(ThreadSelf);
300 return VINF_SUCCESS;
301}
302
303
304/**
305 * Create single connection at a time TCP Server.
306 * The caller must call RTTcpServerListen() to actually start the server.
307 *
308 * @returns iprt status code.
309 * @param pszAddress The address for creating a listening socket.
310 * If NULL the server is bound to all interfaces.
311 * @param uPort The port for creating a listening socket.
312 * @param ppServer Where to store the serverhandle.
313 */
314RTR3DECL(int) RTTcpServerCreateEx(const char *pszAddress, uint32_t uPort, PPRTTCPSERVER ppServer)
315{
316 /*
317 * Validate input.
318 */
319 AssertReturn(uPort > 0, VERR_INVALID_PARAMETER);
320 AssertPtrReturn(ppServer, VERR_INVALID_PARAMETER);
321
322 /*
323 * Resolve the address.
324 */
325 RTNETADDR LocalAddr;
326 int rc = RTSocketParseInetAddress(pszAddress, uPort, &LocalAddr);
327 if (RT_FAILURE(rc))
328 return rc;
329
330 /*
331 * Setting up socket.
332 */
333 RTSOCKET WaitSock;
334 rc = rtSocketCreate(&WaitSock, AF_INET, SOCK_STREAM, IPPROTO_TCP, false /*fInheritable*/);
335 if (RT_SUCCESS(rc))
336 {
337 /*
338 * Set socket options.
339 */
340 int fFlag = 1;
341 if (!rtSocketSetOpt(WaitSock, SOL_SOCKET, SO_REUSEADDR, &fFlag, sizeof(fFlag)))
342 {
343 /*
344 * Bind a name to a socket and set it listening for connections.
345 */
346 rc = rtSocketBind(WaitSock, &LocalAddr);
347 if (RT_SUCCESS(rc))
348 rc = rtSocketListen(WaitSock, RTTCP_SERVER_BACKLOG);
349 if (RT_SUCCESS(rc))
350 {
351 /*
352 * Create the server handle.
353 */
354 PRTTCPSERVER pServer = (PRTTCPSERVER)RTMemPoolAlloc(RTMEMPOOL_DEFAULT, sizeof(*pServer));
355 if (pServer)
356 {
357 pServer->u32Magic = RTTCPSERVER_MAGIC;
358 pServer->enmState = RTTCPSERVERSTATE_CREATED;
359 pServer->Thread = NIL_RTTHREAD;
360 pServer->hServerSocket = WaitSock;
361 pServer->hClientSocket = NIL_RTSOCKET;
362 pServer->pfnServe = NULL;
363 pServer->pvUser = NULL;
364 *ppServer = pServer;
365 return VINF_SUCCESS;
366 }
367
368 /* bail out */
369 rc = VERR_NO_MEMORY;
370 }
371 }
372 else
373 AssertMsgFailed(("rtSocketSetOpt: %Rrc\n", rc));
374 rtTcpClose(WaitSock, "RTServerCreateEx", false /*fTryGracefulShutdown*/);
375 }
376
377 return rc;
378}
379
380
381/**
382 * Listen for incoming connections.
383 *
384 * The function will loop accepting connections and call pfnServe for
385 * each of the incoming connections in turn. The pfnServe function can
386 * return VERR_TCP_SERVER_STOP too terminate this loop. A stopped server
387 * can only be destroyed.
388 *
389 * @returns IPRT status code.
390 * @retval VERR_TCP_SERVER_STOP if stopped by pfnServe.
391 * @retval VERR_TCP_SERVER_SHUTDOWN if shut down by RTTcpServerShutdown.
392 *
393 * @param pServer The server handle as returned from RTTcpServerCreateEx().
394 * @param pfnServe The function which will serve a new client connection.
395 * @param pvUser User argument passed to pfnServe.
396 */
397RTR3DECL(int) RTTcpServerListen(PRTTCPSERVER pServer, PFNRTTCPSERVE pfnServe, void *pvUser)
398{
399 /*
400 * Validate input and retain the instance.
401 */
402 AssertPtrReturn(pfnServe, VERR_INVALID_POINTER);
403 AssertPtrReturn(pServer, VERR_INVALID_HANDLE);
404 AssertReturn(pServer->u32Magic == RTTCPSERVER_MAGIC, VERR_INVALID_HANDLE);
405 AssertReturn(RTMemPoolRetain(pServer) != UINT32_MAX, VERR_INVALID_HANDLE);
406
407 int rc = VERR_INVALID_STATE;
408 if (rtTcpServerTrySetState(pServer, RTTCPSERVERSTATE_ACCEPTING, RTTCPSERVERSTATE_CREATED))
409 {
410 Assert(!pServer->pfnServe);
411 Assert(!pServer->pvUser);
412 Assert(pServer->Thread == NIL_RTTHREAD);
413 Assert(pServer->hClientSocket == NIL_RTSOCKET);
414
415 pServer->pfnServe = pfnServe;
416 pServer->pvUser = pvUser;
417 pServer->Thread = RTThreadSelf();
418 Assert(pServer->Thread != NIL_RTTHREAD);
419 rc = rtTcpServerListen(pServer);
420 }
421 else
422 {
423 AssertMsgFailed(("enmState=%d\n", pServer->enmState));
424 rc = VERR_INVALID_STATE;
425 }
426 RTMemPoolRelease(RTMEMPOOL_DEFAULT, pServer);
427 return rc;
428}
429
430
431/**
432 * Internal worker common for RTTcpServerListen and the thread created by
433 * RTTcpServerCreate().
434 *
435 * The caller makes sure it has its own memory reference and releases it upon
436 * return.
437 */
438static int rtTcpServerListen(PRTTCPSERVER pServer)
439{
440 /*
441 * Accept connection loop.
442 */
443 for (;;)
444 {
445 /*
446 * Change state, getting an extra reference to the socket so we can
447 * allow others to close it while we're stuck in rtSocketAccept.
448 */
449 RTTCPSERVERSTATE enmState = pServer->enmState;
450 RTSOCKET hServerSocket;
451 ASMAtomicXchgHandle(&pServer->hServerSocket, NIL_RTSOCKET, &hServerSocket);
452 if (hServerSocket != NIL_RTSOCKET)
453 {
454 RTSocketRetain(hServerSocket);
455 ASMAtomicWriteHandle(&pServer->hServerSocket, hServerSocket);
456 }
457 if ( enmState != RTTCPSERVERSTATE_ACCEPTING
458 && enmState != RTTCPSERVERSTATE_SERVING)
459 {
460 RTSocketRelease(hServerSocket);
461 return rtTcpServerListenCleanup(pServer);
462 }
463 if (!rtTcpServerTrySetState(pServer, RTTCPSERVERSTATE_ACCEPTING, enmState))
464 {
465 RTSocketRelease(hServerSocket);
466 continue;
467 }
468
469 /*
470 * Accept connection.
471 */
472 struct sockaddr_in RemoteAddr;
473 size_t cbRemoteAddr = sizeof(RemoteAddr);
474 RTSOCKET hClientSocket;
475 RT_ZERO(RemoteAddr);
476 int rc = rtSocketAccept(hServerSocket, &hClientSocket, (struct sockaddr *)&RemoteAddr, &cbRemoteAddr);
477 RTSocketRelease(hServerSocket);
478 if (RT_FAILURE(rc))
479 {
480 /* These are typical for what can happen during destruction. */
481 if ( rc == VERR_INVALID_HANDLE
482 || rc == VERR_INVALID_PARAMETER
483 || rc == VERR_NET_NOT_SOCKET)
484 return rtTcpServerListenCleanup(pServer);
485 continue;
486 }
487 RTSocketSetInheritance(hClientSocket, false /*fInheritable*/);
488
489 /*
490 * Run a pfnServe callback.
491 */
492 if (!rtTcpServerTrySetState(pServer, RTTCPSERVERSTATE_SERVING, RTTCPSERVERSTATE_ACCEPTING))
493 {
494 rtTcpClose(hClientSocket, "rtTcpServerListen", true /*fTryGracefulShutdown*/);
495 return rtTcpServerListenCleanup(pServer);
496 }
497 RTSocketRetain(hClientSocket);
498 rtTcpAtomicXchgSock(&pServer->hClientSocket, hClientSocket);
499 rc = pServer->pfnServe(hClientSocket, pServer->pvUser);
500 rtTcpServerDestroySocket(&pServer->hClientSocket, "Listener: client (secondary)", true /*fTryGracefulShutdown*/);
501 RTSocketRelease(hClientSocket);
502
503 /*
504 * Stop the server?
505 */
506 if (rc == VERR_TCP_SERVER_STOP)
507 {
508 if (rtTcpServerTrySetState(pServer, RTTCPSERVERSTATE_STOPPING, RTTCPSERVERSTATE_SERVING))
509 {
510 /*
511 * Reset the server socket and change the state to stopped. After that state change
512 * we cannot safely access the handle so we'll have to return here.
513 */
514 hServerSocket = rtTcpAtomicXchgSock(&pServer->hServerSocket, NIL_RTSOCKET);
515 rtTcpServerSetState(pServer, RTTCPSERVERSTATE_STOPPED, RTTCPSERVERSTATE_STOPPING);
516 rtTcpClose(hServerSocket, "Listener: server stopped", false /*fTryGracefulShutdown*/);
517 }
518 else
519 rtTcpServerListenCleanup(pServer); /* ignore rc */
520 return rc;
521 }
522 }
523}
524
525
526/**
527 * Clean up after listener.
528 */
529static int rtTcpServerListenCleanup(PRTTCPSERVER pServer)
530{
531 /*
532 * Close the server socket, the client one shouldn't be set.
533 */
534 rtTcpServerDestroySocket(&pServer->hServerSocket, "ListenCleanup", false /*fTryGracefulShutdown*/);
535 Assert(pServer->hClientSocket == NIL_RTSOCKET);
536
537 /*
538 * Figure the return code and make sure the state is OK.
539 */
540 RTTCPSERVERSTATE enmState = pServer->enmState;
541 switch (enmState)
542 {
543 case RTTCPSERVERSTATE_STOPPING:
544 case RTTCPSERVERSTATE_STOPPED:
545 return VERR_TCP_SERVER_SHUTDOWN;
546
547 case RTTCPSERVERSTATE_ACCEPTING:
548 rtTcpServerTrySetState(pServer, RTTCPSERVERSTATE_STOPPED, enmState);
549 return VERR_TCP_SERVER_DESTROYED;
550
551 case RTTCPSERVERSTATE_DESTROYING:
552 return VERR_TCP_SERVER_DESTROYED;
553
554 case RTTCPSERVERSTATE_STARTING:
555 case RTTCPSERVERSTATE_SERVING:
556 default:
557 AssertMsgFailedReturn(("pServer=%p enmState=%d\n", pServer, enmState), VERR_INTERNAL_ERROR_4);
558 }
559}
560
561
562/**
563 * Listen and accept one incoming connection.
564 *
565 * This is an alternative to RTTcpServerListen for the use the callbacks are not
566 * possible.
567 *
568 * @returns IPRT status code.
569 * @retval VERR_TCP_SERVER_SHUTDOWN if shut down by RTTcpServerShutdown.
570 * @retval VERR_INTERRUPTED if the listening was interrupted.
571 *
572 * @param pServer The server handle as returned from RTTcpServerCreateEx().
573 * @param phClientSocket Where to return the socket handle to the client
574 * connection (on success only). This must be closed
575 * by calling RTTcpServerDisconnectClient2().
576 */
577RTR3DECL(int) RTTcpServerListen2(PRTTCPSERVER pServer, PRTSOCKET phClientSocket)
578{
579 /*
580 * Validate input and retain the instance.
581 */
582 AssertPtrReturn(phClientSocket, VERR_INVALID_HANDLE);
583 *phClientSocket = NIL_RTSOCKET;
584 AssertReturn(pServer->u32Magic == RTTCPSERVER_MAGIC, VERR_INVALID_HANDLE);
585 AssertReturn(RTMemPoolRetain(pServer) != UINT32_MAX, VERR_INVALID_HANDLE);
586
587 int rc = VERR_INVALID_STATE;
588 for (;;)
589 {
590 /*
591 * Change state, getting an extra reference to the socket so we can
592 * allow others to close it while we're stuck in rtSocketAccept.
593 */
594 RTTCPSERVERSTATE enmState = pServer->enmState;
595 RTSOCKET hServerSocket;
596 ASMAtomicXchgHandle(&pServer->hServerSocket, NIL_RTSOCKET, &hServerSocket);
597 if (hServerSocket != NIL_RTSOCKET)
598 {
599 RTSocketRetain(hServerSocket);
600 ASMAtomicWriteHandle(&pServer->hServerSocket, hServerSocket);
601 }
602 if ( enmState != RTTCPSERVERSTATE_SERVING
603 && enmState != RTTCPSERVERSTATE_CREATED)
604 {
605 RTSocketRelease(hServerSocket);
606 return rtTcpServerListenCleanup(pServer);
607 }
608 if (!rtTcpServerTrySetState(pServer, RTTCPSERVERSTATE_ACCEPTING, enmState))
609 {
610 RTSocketRelease(hServerSocket);
611 continue;
612 }
613 Assert(!pServer->pfnServe);
614 Assert(!pServer->pvUser);
615 Assert(pServer->Thread == NIL_RTTHREAD);
616 Assert(pServer->hClientSocket == NIL_RTSOCKET);
617
618 /*
619 * Accept connection.
620 */
621 struct sockaddr_in RemoteAddr;
622 size_t cbRemoteAddr = sizeof(RemoteAddr);
623 RTSOCKET hClientSocket;
624 RT_ZERO(RemoteAddr);
625 rc = rtSocketAccept(hServerSocket, &hClientSocket, (struct sockaddr *)&RemoteAddr, &cbRemoteAddr);
626 RTSocketRelease(hServerSocket);
627 if (RT_FAILURE(rc))
628 {
629 if (!rtTcpServerTrySetState(pServer, RTTCPSERVERSTATE_CREATED, RTTCPSERVERSTATE_ACCEPTING))
630 rc = rtTcpServerListenCleanup(pServer);
631 if (RT_FAILURE(rc))
632 break;
633 continue;
634 }
635 RTSocketSetInheritance(hClientSocket, false /*fInheritable*/);
636
637 /*
638 * Chance to the 'serving' state and return the socket.
639 */
640 if (rtTcpServerTrySetState(pServer, RTTCPSERVERSTATE_SERVING, RTTCPSERVERSTATE_ACCEPTING))
641 {
642 *phClientSocket = hClientSocket;
643 rc = VINF_SUCCESS;
644 }
645 else
646 {
647 rtTcpClose(hClientSocket, "RTTcpServerListen2", true /*fTryGracefulShutdown*/);
648 rc = rtTcpServerListenCleanup(pServer);
649 }
650 break;
651 }
652
653 RTMemPoolRelease(RTMEMPOOL_DEFAULT, pServer);
654 return rc;
655}
656
657
658/**
659 * Terminate the open connection to the server.
660 *
661 * @returns iprt status code.
662 * @param pServer Handle to the server.
663 */
664RTR3DECL(int) RTTcpServerDisconnectClient(PRTTCPSERVER pServer)
665{
666 /*
667 * Validate input and retain the instance.
668 */
669 AssertPtrReturn(pServer, VERR_INVALID_HANDLE);
670 AssertReturn(pServer->u32Magic == RTTCPSERVER_MAGIC, VERR_INVALID_HANDLE);
671 AssertReturn(RTMemPoolRetain(pServer) != UINT32_MAX, VERR_INVALID_HANDLE);
672
673 int rc = rtTcpServerDestroySocket(&pServer->hClientSocket, "DisconnectClient: client", true /*fTryGracefulShutdown*/);
674
675 RTMemPoolRelease(RTMEMPOOL_DEFAULT, pServer);
676 return rc;
677}
678
679
680/**
681 * Terminates an open client connect when using RTTcpListen2
682 *
683 * @returns IPRT status code.
684 * @param hClientSocket The client socket handle. This will be invalid upon
685 * return, whether successful or not. NIL is quietly
686 * ignored (VINF_SUCCESS).
687 */
688RTR3DECL(int) RTTcpServerDisconnectClient2(RTSOCKET hClientSocket)
689{
690 return rtTcpClose(hClientSocket, "RTTcpServerDisconnectClient2", true /*fTryGracefulShutdown*/);
691}
692
693
694/**
695 * Shuts down the server, leaving client connections open.
696 *
697 * @returns IPRT status code.
698 * @param pServer Handle to the server.
699 */
700RTR3DECL(int) RTTcpServerShutdown(PRTTCPSERVER pServer)
701{
702 /*
703 * Validate input and retain the instance.
704 */
705 AssertPtrReturn(pServer, VERR_INVALID_HANDLE);
706 AssertReturn(pServer->u32Magic == RTTCPSERVER_MAGIC, VERR_INVALID_HANDLE);
707 AssertReturn(RTMemPoolRetain(pServer) != UINT32_MAX, VERR_INVALID_HANDLE);
708
709 /*
710 * Try change the state to stopping, then replace and destroy the server socket.
711 */
712 for (;;)
713 {
714 RTTCPSERVERSTATE enmState = pServer->enmState;
715 if ( enmState != RTTCPSERVERSTATE_ACCEPTING
716 && enmState != RTTCPSERVERSTATE_SERVING)
717 {
718 RTMemPoolRelease(RTMEMPOOL_DEFAULT, pServer);
719 switch (enmState)
720 {
721 case RTTCPSERVERSTATE_CREATED:
722 case RTTCPSERVERSTATE_STARTING:
723 default:
724 AssertMsgFailed(("%d\n", enmState));
725 return VERR_INVALID_STATE;
726
727 case RTTCPSERVERSTATE_STOPPING:
728 case RTTCPSERVERSTATE_STOPPED:
729 return VINF_SUCCESS;
730
731 case RTTCPSERVERSTATE_DESTROYING:
732 return VERR_TCP_SERVER_DESTROYED;
733 }
734 }
735 if (rtTcpServerTrySetState(pServer, RTTCPSERVERSTATE_STOPPING, enmState))
736 {
737 rtTcpServerDestroySocket(&pServer->hServerSocket, "RTTcpServerShutdown", false /*fTryGracefulShutdown*/);
738 rtTcpServerSetState(pServer, RTTCPSERVERSTATE_STOPPED, RTTCPSERVERSTATE_STOPPING);
739
740 RTMemPoolRelease(RTMEMPOOL_DEFAULT, pServer);
741 return VINF_SUCCESS;
742 }
743 }
744}
745
746
747/**
748 * Closes down and frees a TCP Server.
749 * This will also terminate any open connections to the server.
750 *
751 * @returns iprt status code.
752 * @param pServer Handle to the server.
753 */
754RTR3DECL(int) RTTcpServerDestroy(PRTTCPSERVER pServer)
755{
756 /*
757 * Validate input and retain the instance.
758 */
759 AssertPtrReturn(pServer, VERR_INVALID_HANDLE);
760 AssertReturn(pServer->u32Magic == RTTCPSERVER_MAGIC, VERR_INVALID_HANDLE);
761 AssertReturn(RTMemPoolRetain(pServer) != UINT32_MAX, VERR_INVALID_HANDLE); /* paranoia */
762
763 /*
764 * Move the state along so the listener can figure out what's going on.
765 */
766 for (;;)
767 {
768 bool fDestroyable;
769 RTTCPSERVERSTATE enmState = pServer->enmState;
770 switch (enmState)
771 {
772 case RTTCPSERVERSTATE_STARTING:
773 case RTTCPSERVERSTATE_ACCEPTING:
774 case RTTCPSERVERSTATE_SERVING:
775 case RTTCPSERVERSTATE_CREATED:
776 case RTTCPSERVERSTATE_STOPPED:
777 fDestroyable = rtTcpServerTrySetState(pServer, RTTCPSERVERSTATE_DESTROYING, enmState);
778 break;
779
780 /* destroyable states */
781 case RTTCPSERVERSTATE_STOPPING:
782 fDestroyable = true;
783 break;
784
785 /*
786 * Everything else means user or internal misbehavior.
787 */
788 default:
789 AssertMsgFailed(("pServer=%p enmState=%d\n", pServer, enmState));
790 RTMemPoolRelease(RTMEMPOOL_DEFAULT, pServer);
791 return VERR_INTERNAL_ERROR;
792 }
793 if (fDestroyable)
794 break;
795 }
796
797 /*
798 * Destroy it.
799 */
800 ASMAtomicWriteU32(&pServer->u32Magic, ~RTTCPSERVER_MAGIC);
801 rtTcpServerDestroySocket(&pServer->hServerSocket, "Destroyer: server", false /*fTryGracefulShutdown*/);
802 rtTcpServerDestroySocket(&pServer->hClientSocket, "Destroyer: client", true /*fTryGracefulShutdown*/);
803
804 /*
805 * Release it.
806 */
807 RTMemPoolRelease(RTMEMPOOL_DEFAULT, pServer);
808 RTMemPoolRelease(RTMEMPOOL_DEFAULT, pServer);
809 return VINF_SUCCESS;
810}
811
812
813RTR3DECL(int) RTTcpClientConnect(const char *pszAddress, uint32_t uPort, PRTSOCKET pSock)
814{
815 return RTTcpClientConnectEx(pszAddress, uPort, pSock, RT_SOCKETCONNECT_DEFAULT_WAIT, NULL);
816}
817
818
819RTR3DECL(int) RTTcpClientConnectEx(const char *pszAddress, uint32_t uPort, PRTSOCKET pSock,
820 RTMSINTERVAL cMillies, PRTTCPCLIENTCONNECTCANCEL volatile *ppCancelCookie)
821{
822 /*
823 * Validate input.
824 */
825 AssertReturn(uPort > 0, VERR_INVALID_PARAMETER);
826 AssertPtrReturn(pszAddress, VERR_INVALID_POINTER);
827 AssertPtrNullReturn(ppCancelCookie, VERR_INVALID_POINTER);
828
829 /*
830 * Resolve the address.
831 */
832 RTNETADDR Addr;
833 int rc = RTSocketParseInetAddress(pszAddress, uPort, &Addr);
834 if (RT_FAILURE(rc))
835 return rc;
836
837 /*
838 * Create the socket and connect.
839 */
840 RTSOCKET Sock;
841 rc = rtSocketCreate(&Sock, PF_INET, SOCK_STREAM, 0, false /*fInheritable*/);
842 if (RT_SUCCESS(rc))
843 {
844 if (!ppCancelCookie)
845 rc = rtSocketConnect(Sock, &Addr, cMillies);
846 else
847 {
848 RTSocketRetain(Sock);
849 if (ASMAtomicCmpXchgPtr(ppCancelCookie, (PRTTCPCLIENTCONNECTCANCEL)Sock, NULL))
850 {
851 rc = rtSocketConnect(Sock, &Addr, cMillies);
852 if (ASMAtomicCmpXchgPtr(ppCancelCookie, NULL, (PRTTCPCLIENTCONNECTCANCEL)Sock))
853 RTSocketRelease(Sock);
854 else
855 rc = VERR_CANCELLED;
856 }
857 else
858 {
859 RTSocketRelease(Sock);
860 rc = VERR_CANCELLED;
861 }
862 }
863 if (RT_SUCCESS(rc))
864 {
865 *pSock = Sock;
866 return VINF_SUCCESS;
867 }
868
869 rtTcpClose(Sock, "RTTcpClientConnect", false /*fTryGracefulShutdown*/);
870 }
871 if (ppCancelCookie)
872 *ppCancelCookie = NULL;
873 return rc;
874}
875
876
877RTR3DECL(int) RTTcpClientCancelConnect(PRTTCPCLIENTCONNECTCANCEL volatile *ppCancelCookie)
878{
879 AssertPtrReturn(ppCancelCookie, VERR_INVALID_POINTER);
880
881 RTSOCKET const hSockCancelled = (RTSOCKET)(uintptr_t)0xdead9999;
882
883 AssertCompile(NIL_RTSOCKET == NULL);
884 RTSOCKET hSock = (RTSOCKET)ASMAtomicXchgPtr((void * volatile *)ppCancelCookie, hSockCancelled);
885 if (hSock != NIL_RTSOCKET && hSock != hSockCancelled)
886 {
887 int rc = rtTcpClose(hSock, "RTTcpClientCancelConnect", false /*fTryGracefulShutdown*/);
888 AssertRCReturn(rc, rc);
889 }
890
891 return VINF_SUCCESS;
892}
893
894
895RTR3DECL(int) RTTcpClientClose(RTSOCKET Sock)
896{
897 return rtTcpClose(Sock, "RTTcpClientClose", true /*fTryGracefulShutdown*/);
898}
899
900
901RTR3DECL(int) RTTcpClientCloseEx(RTSOCKET Sock, bool fGracefulShutdown)
902{
903 return rtTcpClose(Sock, "RTTcpClientCloseEx", fGracefulShutdown);
904}
905
906
907#ifdef FIX_FOR_3_2
908/**
909 * Changes the blocking mode of the socket.
910 *
911 * @returns 0 on success, -1 on failure.
912 * @param hSocket The socket to work on.
913 * @param fBlocking The desired mode of operation.
914 */
915static int rtTcpSetBlockingMode(RTHCUINTPTR hSocket, bool fBlocking)
916{
917 int rc = VINF_SUCCESS;
918#ifdef RT_OS_WINDOWS
919 u_long uBlocking = fBlocking ? 0 : 1;
920 if (ioctlsocket(hSocket, FIONBIO, &uBlocking))
921 return -1;
922
923#else
924 int fFlags = fcntl(hSocket, F_GETFL, 0);
925 if (fFlags == -1)
926 return -1;
927
928 if (fBlocking)
929 fFlags &= ~O_NONBLOCK;
930 else
931 fFlags |= O_NONBLOCK;
932 if (fcntl(hSocket, F_SETFL, fFlags) == -1)
933 return -1;
934#endif
935
936 return 0;
937}
938#endif
939
940
941/**
942 * Internal close function which does all the proper bitching.
943 */
944static int rtTcpClose(RTSOCKET Sock, const char *pszMsg, bool fTryGracefulShutdown)
945{
946 NOREF(pszMsg); /** @todo drop this parameter? */
947
948 /* ignore nil handles. */
949 if (Sock == NIL_RTSOCKET)
950 return VINF_SUCCESS;
951
952 /*
953 * Try to gracefully shut it down.
954 */
955 int rc;
956 if (fTryGracefulShutdown)
957 {
958 rc = RTSocketShutdown(Sock, false /*fRead*/, true /*fWrite*/);
959#ifdef FIX_FOR_3_2
960 RTHCUINTPTR hNative = RTSocketToNative(Sock);
961 if (RT_SUCCESS(rc) && rtTcpSetBlockingMode(hNative, false /*fBlocking*/) == 0)
962#else
963 if (RT_SUCCESS(rc))
964#endif
965 {
966
967 size_t cbReceived = 0;
968 uint64_t u64Start = RTTimeMilliTS();
969 while ( cbReceived < _1G
970 && RTTimeMilliTS() - u64Start < 30000)
971 {
972#ifdef FIX_FOR_3_2
973 fd_set FdSetR;
974 FD_ZERO(&FdSetR);
975 FD_SET(hNative, &FdSetR);
976
977 fd_set FdSetE;
978 FD_ZERO(&FdSetE);
979 FD_SET(hNative, &FdSetE);
980
981 struct timeval TvTimeout;
982 TvTimeout.tv_sec = 1;
983 TvTimeout.tv_usec = 0;
984 rc = select(hNative + 1, &FdSetR, NULL, &FdSetE, &TvTimeout);
985 if (rc == 0)
986 continue;
987 if (rc < 0)
988 break;
989 if (FD_ISSET(hNative, &FdSetE))
990 break;
991#else
992 uint32_t fEvents;
993 rc = RTSocketSelectOneEx(Sock, RTSOCKET_EVT_READ | RTSOCKET_EVT_ERROR, &fEvents, 1000);
994 if (rc == VERR_TIMEOUT)
995 continue;
996 if (RT_FAILURE(rc))
997 break;
998 if (fEvents & RTSOCKET_EVT_ERROR)
999 break;
1000#endif
1001
1002 char abBitBucket[16*_1K];
1003#ifdef FIX_FOR_3_2
1004 ssize_t cbRead = recv(hNative, &abBitBucket[0], sizeof(abBitBucket), MSG_NOSIGNAL);
1005 if (cbRead == 0)
1006 break; /* orderly shutdown in progress */
1007 if (cbRead < 0 && errno != EAGAIN)
1008 break; /* some kind of error, never mind which... */
1009#else
1010 size_t cbRead;
1011 rc = RTSocketReadNB(Sock, &abBitBucket[0], sizeof(abBitBucket), &cbRead);
1012 if (RT_FAILURE(rc))
1013 break; /* some kind of error, never mind which... */
1014 if (rc != VINF_TRY_AGAIN && !cbRead)
1015 break; /* orderly shutdown in progress */
1016#endif
1017
1018 cbReceived += cbRead;
1019 }
1020 }
1021 }
1022
1023 /*
1024 * Close the socket handle (drops our reference to it).
1025 */
1026 return RTSocketClose(Sock);
1027}
1028
1029
1030/**
1031 * Creates connected pair of TCP sockets.
1032 *
1033 * @returns IPRT status code.
1034 * @param phServer Where to return the "server" side of the pair.
1035 * @param phClient Where to return the "client" side of the pair.
1036 *
1037 * @note There is no server or client side, but we gotta call it something.
1038 */
1039RTR3DECL(int) RTTcpCreatePair(PRTSOCKET phServer, PRTSOCKET phClient, uint32_t fFlags)
1040{
1041 /*
1042 * Validate input.
1043 */
1044 AssertPtrReturn(phServer, VERR_INVALID_PARAMETER);
1045 AssertPtrReturn(phClient, VERR_INVALID_PARAMETER);
1046 AssertReturn(!fFlags, VERR_INVALID_PARAMETER);
1047
1048 /*
1049 * Do the job.
1050 */
1051 return rtSocketCreateTcpPair(phServer, phClient);
1052}
1053
1054
1055RTR3DECL(int) RTTcpRead(RTSOCKET Sock, void *pvBuffer, size_t cbBuffer, size_t *pcbRead)
1056{
1057 return RTSocketRead(Sock, pvBuffer, cbBuffer, pcbRead);
1058}
1059
1060
1061RTR3DECL(int) RTTcpWrite(RTSOCKET Sock, const void *pvBuffer, size_t cbBuffer)
1062{
1063 return RTSocketWrite(Sock, pvBuffer, cbBuffer);
1064}
1065
1066
1067RTR3DECL(int) RTTcpFlush(RTSOCKET Sock)
1068{
1069 int fFlag = 1;
1070 int rc = rtSocketSetOpt(Sock, IPPROTO_TCP, TCP_NODELAY, &fFlag, sizeof(fFlag));
1071 if (RT_SUCCESS(rc))
1072 {
1073 fFlag = 0;
1074 rc = rtSocketSetOpt(Sock, IPPROTO_TCP, TCP_NODELAY, &fFlag, sizeof(fFlag));
1075 }
1076 return rc;
1077}
1078
1079
1080RTR3DECL(int) RTTcpSetSendCoalescing(RTSOCKET Sock, bool fEnable)
1081{
1082 int fFlag = fEnable ? 0 : 1;
1083 return rtSocketSetOpt(Sock, IPPROTO_TCP, TCP_NODELAY, &fFlag, sizeof(fFlag));
1084}
1085
1086
1087RTR3DECL(int) RTTcpSetBufferSize(RTSOCKET hSocket, uint32_t cbSize)
1088{
1089 int cbIntSize = (int)cbSize;
1090 AssertReturn(cbIntSize >= 0, VERR_OUT_OF_RANGE);
1091 int rc = rtSocketSetOpt(hSocket, SOL_SOCKET, SO_SNDBUF, &cbIntSize, sizeof(cbIntSize));
1092 if (RT_SUCCESS(rc))
1093 rc = rtSocketSetOpt(hSocket, SOL_SOCKET, SO_RCVBUF, &cbIntSize, sizeof(cbIntSize));
1094 return rc;
1095}
1096
1097
1098RTR3DECL(int) RTTcpSelectOne(RTSOCKET Sock, RTMSINTERVAL cMillies)
1099{
1100 return RTSocketSelectOne(Sock, cMillies);
1101}
1102
1103
1104RTR3DECL(int) RTTcpSelectOneEx(RTSOCKET Sock, uint32_t fEvents, uint32_t *pfEvents,
1105 RTMSINTERVAL cMillies)
1106{
1107 return RTSocketSelectOneEx(Sock, fEvents, pfEvents, cMillies);
1108}
1109
1110
1111RTR3DECL(int) RTTcpGetLocalAddress(RTSOCKET Sock, PRTNETADDR pAddr)
1112{
1113 return RTSocketGetLocalAddress(Sock, pAddr);
1114}
1115
1116
1117RTR3DECL(int) RTTcpGetPeerAddress(RTSOCKET Sock, PRTNETADDR pAddr)
1118{
1119 return RTSocketGetPeerAddress(Sock, pAddr);
1120}
1121
1122
1123RTR3DECL(int) RTTcpSgWrite(RTSOCKET Sock, PCRTSGBUF pSgBuf)
1124{
1125 return RTSocketSgWrite(Sock, pSgBuf);
1126}
1127
1128
1129RTR3DECL(int) RTTcpSgWriteL(RTSOCKET hSocket, size_t cSegs, ...)
1130{
1131 va_list va;
1132 va_start(va, cSegs);
1133 int rc = RTSocketSgWriteLV(hSocket, cSegs, va);
1134 va_end(va);
1135 return rc;
1136}
1137
1138
1139RTR3DECL(int) RTTcpSgWriteLV(RTSOCKET hSocket, size_t cSegs, va_list va)
1140{
1141 return RTSocketSgWriteLV(hSocket, cSegs, va);
1142}
1143
1144
1145RTR3DECL(int) RTTcpReadNB(RTSOCKET Sock, void *pvBuffer, size_t cbBuffer, size_t *pcbRead)
1146{
1147 return RTSocketReadNB(Sock, pvBuffer, cbBuffer, pcbRead);
1148}
1149
1150
1151RTR3DECL(int) RTTcpWriteNB(RTSOCKET Sock, const void *pvBuffer, size_t cbBuffer, size_t *pcbWritten)
1152{
1153 return RTSocketWriteNB(Sock, pvBuffer, cbBuffer, pcbWritten);
1154}
1155
1156
1157RTR3DECL(int) RTTcpSgWriteNB(RTSOCKET Sock, PCRTSGBUF pSgBuf, size_t *pcbWritten)
1158{
1159 return RTSocketSgWriteNB(Sock, pSgBuf, pcbWritten);
1160}
1161
1162
1163RTR3DECL(int) RTTcpSgWriteLNB(RTSOCKET hSocket, size_t cSegs, size_t *pcbWritten, ...)
1164{
1165 va_list va;
1166 va_start(va, pcbWritten);
1167 int rc = RTSocketSgWriteLVNB(hSocket, cSegs, pcbWritten, va);
1168 va_end(va);
1169 return rc;
1170}
1171
1172
1173RTR3DECL(int) RTTcpSgWriteLVNB(RTSOCKET hSocket, size_t cSegs, size_t *pcbWritten, va_list va)
1174{
1175 return RTSocketSgWriteLVNB(hSocket, cSegs, pcbWritten, va);
1176}
1177
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