VirtualBox

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

Last change on this file since 25409 was 25000, checked in by vboxsync, 15 years ago

IPRT: Fixed -Wshadow warnings, found two bugs in error paths.

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