tcp.cpp revision b34bbc1afcc3a1d2bfbb9814f95a965abd8563e2
/* $Id$ */
/** @file
*/
/*
* Copyright (C) 2006-2010 Oracle Corporation
*
* This file is part of VirtualBox Open Source Edition (OSE), as
* available from http://www.virtualbox.org. This file is free software;
* General Public License (GPL) as published by the Free Software
* Foundation, in version 2 as it comes in the "COPYING" file of the
* VirtualBox OSE distribution. VirtualBox OSE is distributed in the
* hope that it will be useful, but WITHOUT ANY WARRANTY of any kind.
*
* The contents of this file may alternatively be used under the terms
* of the Common Development and Distribution License Version 1.0
* (CDDL) only, as it comes in the "COPYING.CDDL" file of the
* VirtualBox OSE distribution, in which case the provisions of the
* CDDL are applicable instead of those of the GPL.
*
* You may elect to license modified versions of this file under the
* terms and conditions of either the GPL or the CDDL or both.
*/
/*******************************************************************************
* Header Files *
*******************************************************************************/
#ifdef RT_OS_WINDOWS
# include <winsock2.h>
#else
# include <errno.h>
# include <netdb.h>
# ifdef FIX_FOR_3_2
# include <fcntl.h>
# endif
#endif
#include <limits.h>
/*******************************************************************************
* Defined Constants And Macros *
*******************************************************************************/
/* non-standard linux stuff (it seems). */
#ifndef MSG_NOSIGNAL
# define MSG_NOSIGNAL 0
#endif
#ifndef SHUT_RDWR
# ifdef SD_BOTH
# else
# define SHUT_RDWR 2
# endif
#endif
#ifndef SHUT_WR
# ifdef SD_SEND
# else
# define SHUT_WR 1
# endif
#endif
/* fixup backlevel OSes. */
#if defined(RT_OS_OS2) || defined(RT_OS_WINDOWS)
# define socklen_t int
#endif
/** How many pending connection. */
#define RTTCP_SERVER_BACKLOG 10
/*******************************************************************************
* Structures and Typedefs *
*******************************************************************************/
/**
* TCP Server state.
*/
typedef enum RTTCPSERVERSTATE
{
/** Invalid. */
/** Created. */
/** Listener thread is starting up. */
/** Accepting client connections. */
/** Serving a client. */
/** Listener terminating. */
/** Listener terminated. */
/** Listener cleans up. */
/*
* Internal representation of the TCP Server handle.
*/
typedef struct RTTCPSERVER
{
/** The magic value (RTTCPSERVER_MAGIC). */
/** The server state. */
RTTCPSERVERSTATE volatile enmState;
/** The server thread. */
/** The server socket. */
RTSOCKET volatile hServerSocket;
/** The socket to the client currently being serviced.
* This is NIL_RTSOCKET when no client is serviced. */
RTSOCKET volatile hClientSocket;
/** The connection function. */
/** Argument to pfnServer. */
void *pvUser;
} RTTCPSERVER;
/*******************************************************************************
* Internal Functions *
*******************************************************************************/
/**
* Atomicly updates a socket variable.
* @returns The old handle value.
* @param phSock The socket handle variable to update.
* @param hSock The new socket handle value.
*/
{
return hRet;
}
/**
* Tries to change the TCP server state.
*/
DECLINLINE(bool) rtTcpServerTrySetState(PRTTCPSERVER pServer, RTTCPSERVERSTATE enmStateNew, RTTCPSERVERSTATE enmStateOld)
{
bool fRc;
return fRc;
}
/**
* Changes the TCP server state.
*/
DECLINLINE(void) rtTcpServerSetState(PRTTCPSERVER pServer, RTTCPSERVERSTATE enmStateNew, RTTCPSERVERSTATE enmStateOld)
{
bool fRc;
}
/**
* Closes the a socket (client or server).
*
* @returns IPRT status code.
*/
static int rtTcpServerDestroySocket(RTSOCKET volatile *pSock, const char *pszMsg, bool fTryGracefulShutdown)
{
if (hSocket != NIL_RTSOCKET)
{
if (!fTryGracefulShutdown)
}
return VINF_TCP_SERVER_NO_CLIENT;
}
/**
* Create single connection at a time TCP Server in a separate thread.
*
* The thread will loop accepting connections and call pfnServe for
* each of the incoming connections in turn. The pfnServe function can
* return VERR_TCP_SERVER_STOP too terminate this loop. RTTcpServerDestroy()
* should be used to terminate the server.
*
* @returns iprt status code.
* @param pszAddress The address for creating a listening socket.
* If NULL or empty string the server is bound to all interfaces.
* @param uPort The port for creating a listening socket.
* @param enmType The thread type.
* @param pszThrdName The name of the worker thread.
* @param pfnServe The function which will serve a new client connection.
* @param pvUser User argument passed to pfnServe.
* @param ppServer Where to store the serverhandle.
*/
RTR3DECL(int) RTTcpServerCreate(const char *pszAddress, unsigned uPort, RTTHREADTYPE enmType, const char *pszThrdName,
{
/*
* Validate input.
*/
/*
* Create the server.
*/
if (RT_SUCCESS(rc))
{
/*
* Create the listener thread.
*/
rc = RTThreadCreate(&pServer->Thread, rtTcpServerThread, pServer, 0, enmType, /*RTTHREADFLAGS_WAITABLE*/0, pszThrdName);
if (RT_SUCCESS(rc))
{
/* done */
if (ppServer)
else
return rc;
}
/*
* Destroy the server.
*/
}
return rc;
}
/**
* Server thread, loops accepting connections until it's terminated.
*
* @returns iprt status code. (ignored).
* @param ThreadSelf Thread handle.
* @param pvServer Server handle.
*/
{
int rc;
else
return VINF_SUCCESS;
}
/**
* Create single connection at a time TCP Server.
* The caller must call RTTcpServerListen() to actually start the server.
*
* @returns iprt status code.
* @param pszAddress The address for creating a listening socket.
* If NULL the server is bound to all interfaces.
* @param uPort The port for creating a listening socket.
* @param ppServer Where to store the serverhandle.
*/
{
int rc;
/*
* Validate input.
*/
#ifdef RT_OS_WINDOWS
/*
* Initialize WinSock and check version.
*/
{
AssertMsgFailed(("Wrong winsock version\n"));
return VERR_NOT_SUPPORTED;
}
#endif
/*
* Get host listening address.
*/
{
if (!pHostEnt)
{
if (!pHostEnt)
{
rc = rtSocketResolverError();
return rc;
}
}
}
/*
* Setting up socket.
*/
if (RT_SUCCESS(rc))
{
/*
* Set socket options.
*/
int fFlag = 1;
{
/*
* Set socket family, address and port.
*/
struct sockaddr_in LocalAddr;
/* if address not specified, use INADDR_ANY. */
if (!pHostEnt)
else
/*
* Bind a name to a socket and set it listening for connections.
*/
if (RT_SUCCESS(rc))
if (RT_SUCCESS(rc))
{
/*
* Create the server handle.
*/
if (pServer)
{
return VINF_SUCCESS;
}
/* bail out */
rc = VERR_NO_MEMORY;
}
}
else
}
return rc;
}
/**
* Listen for incoming connections.
*
* The function will loop accepting connections and call pfnServe for
* each of the incoming connections in turn. The pfnServe function can
* return VERR_TCP_SERVER_STOP too terminate this loop. A stopped server
* can only be destroyed.
*
* @returns IPRT status code.
* @retval VERR_TCP_SERVER_STOP if stopped by pfnServe.
* @retval VERR_TCP_SERVER_SHUTDOWN if shut down by RTTcpServerShutdown.
*
* @param pServer The server handle as returned from RTTcpServerCreateEx().
* @param pfnServe The function which will serve a new client connection.
* @param pvUser User argument passed to pfnServe.
*/
{
/*
* Validate input and retain the instance.
*/
int rc = VERR_INVALID_STATE;
{
}
else
{
}
return rc;
}
/**
* Internal worker common for RTTcpServerListen and the thread created by
* RTTcpServerCreate().
*
* The caller makes sure it has its own memory reference and releases it upon
* return.
*/
{
/*
* Accept connection loop.
*/
for (;;)
{
/*
* Change state, getting an extra reference to the socket so we can
* allow others to close it while we're stuck in rtSocketAccept.
*/
if (hServerSocket != NIL_RTSOCKET)
{
}
if ( enmState != RTTCPSERVERSTATE_ACCEPTING
&& enmState != RTTCPSERVERSTATE_SERVING)
{
return rtTcpServerListenCleanup(pServer);
}
{
continue;
}
/*
* Accept connection.
*/
struct sockaddr_in RemoteAddr;
int rc = rtSocketAccept(hServerSocket, &hClientSocket, (struct sockaddr *)&RemoteAddr, &cbRemoteAddr);
if (RT_FAILURE(rc))
{
/* These are typical for what can happen during destruction. */
if ( rc == VERR_INVALID_HANDLE
|| rc == VERR_INVALID_PARAMETER
|| rc == VERR_NET_NOT_SOCKET)
return rtTcpServerListenCleanup(pServer);
continue;
}
/*
* Run a pfnServe callback.
*/
{
return rtTcpServerListenCleanup(pServer);
}
rtTcpServerDestroySocket(&pServer->hClientSocket, "Listener: client (secondary)", true /*fTryGracefulShutdown*/);
/*
* Stop the server?
*/
if (rc == VERR_TCP_SERVER_STOP)
{
{
/*
* Reset the server socket and change the state to stopped. After that state change
* we cannot safely access the handle so we'll have to return here.
*/
}
else
return rc;
}
}
}
/**
* Clean up after listener.
*/
{
/*
* Close the server socket, the client one shouldn't be set.
*/
/*
* Figure the return code and make sure the state is OK.
*/
switch (enmState)
{
case RTTCPSERVERSTATE_STOPPED:
return VERR_TCP_SERVER_SHUTDOWN;
return VERR_TCP_SERVER_DESTROYED;
return VERR_TCP_SERVER_DESTROYED;
case RTTCPSERVERSTATE_SERVING:
default:
}
}
/**
* Listen and accept one incomming connection.
*
* This is an alternative to RTTcpServerListen for the use the callbacks are not
* possible.
*
* @returns IPRT status code.
* @retval VERR_TCP_SERVER_SHUTDOWN if shut down by RTTcpServerShutdown.
* @retval VERR_INTERRUPTED if the listening was interrupted.
*
* @param pServer The server handle as returned from RTTcpServerCreateEx().
* @param phClientSocket Where to return the socket handle to the client
* connection (on success only). This must be closed
* by calling RTTcpServerDisconnectClient2().
*/
{
/*
* Validate input and retain the instance.
*/
int rc = VERR_INVALID_STATE;
for (;;)
{
/*
* Change state, getting an extra reference to the socket so we can
* allow others to close it while we're stuck in rtSocketAccept.
*/
if (hServerSocket != NIL_RTSOCKET)
{
}
if ( enmState != RTTCPSERVERSTATE_SERVING
&& enmState != RTTCPSERVERSTATE_CREATED)
{
return rtTcpServerListenCleanup(pServer);
}
{
continue;
}
/*
* Accept connection.
*/
struct sockaddr_in RemoteAddr;
if (RT_FAILURE(rc))
{
if (RT_FAILURE(rc))
break;
continue;
}
/*
* Chance to the 'serving' state and return the socket.
*/
{
rc = VINF_SUCCESS;
}
else
{
}
break;
}
return rc;
}
/**
* Terminate the open connection to the server.
*
* @returns iprt status code.
* @param pServer Handle to the server.
*/
{
/*
* Validate input and retain the instance.
*/
int rc = rtTcpServerDestroySocket(&pServer->hClientSocket, "DisconnectClient: client", true /*fTryGracefulShutdown*/);
return rc;
}
/**
* Terminates an open client connect when using RTTcpListen2
*
* @returns IPRT status code.
* @param hClientSocket The client socket handle. This will be invalid upon
* return, whether successful or not. NIL is quietly
* ignored (VINF_SUCCESS).
*/
{
}
/**
* Shuts down the server, leaving client connections open.
*
* @returns IPRT status code.
* @param pServer Handle to the server.
*/
{
/*
* Validate input and retain the instance.
*/
/*
* Try change the state to stopping, then replace and destroy the server socket.
*/
for (;;)
{
if ( enmState != RTTCPSERVERSTATE_ACCEPTING
&& enmState != RTTCPSERVERSTATE_SERVING)
{
switch (enmState)
{
case RTTCPSERVERSTATE_CREATED:
default:
return VERR_INVALID_STATE;
case RTTCPSERVERSTATE_STOPPED:
return VINF_SUCCESS;
return VERR_TCP_SERVER_DESTROYED;
}
}
{
rtTcpServerDestroySocket(&pServer->hServerSocket, "RTTcpServerShutdown", false /*fTryGracefulShutdown*/);
return VINF_SUCCESS;
}
}
}
/**
* Closes down and frees a TCP Server.
* This will also terminate any open connections to the server.
*
* @returns iprt status code.
* @param pServer Handle to the server.
*/
{
/*
* Validate input and retain the instance.
*/
/*
* Move the state along so the listener can figure out what's going on.
*/
for (;;)
{
bool fDestroyable;
switch (enmState)
{
case RTTCPSERVERSTATE_SERVING:
case RTTCPSERVERSTATE_CREATED:
case RTTCPSERVERSTATE_STOPPED:
break;
/* destroyable states */
fDestroyable = true;
break;
/*
* Everything else means user or internal misbehavior.
*/
default:
return VERR_INTERNAL_ERROR;
}
if (fDestroyable)
break;
}
/*
* Destroy it.
*/
rtTcpServerDestroySocket(&pServer->hServerSocket, "Destroyer: server", false /*fTryGracefulShutdown*/);
rtTcpServerDestroySocket(&pServer->hClientSocket, "Destroyer: client", true /*fTryGracefulShutdown*/);
/*
* Release it.
*/
return VINF_SUCCESS;
}
{
int rc;
/*
* Validate input.
*/
#ifdef RT_OS_WINDOWS
/*
* Initialize WinSock and check version.
*/
{
AssertMsgFailed(("Wrong winsock version\n"));
return VERR_NOT_SUPPORTED;
}
#endif
/*
* Resolve the address.
*/
if (!pHostEnt)
{
if (!pHostEnt)
{
rc = rtSocketResolverError();
return rc;
}
}
/*
* Create the socket and connect.
*/
if (RT_SUCCESS(rc))
{
struct sockaddr_in InAddr;
if (RT_SUCCESS(rc))
{
return VINF_SUCCESS;
}
}
return rc;
}
{
}
#ifdef FIX_FOR_3_2
/**
* Changes the blocking mode of the socket.
*
* @returns 0 on success, -1 on failure.
* @param hSocket The socket to work on.
* @param fBlocking The desired mode of operation.
*/
{
int rc = VINF_SUCCESS;
#ifdef RT_OS_WINDOWS
return -1;
#else
if (fFlags == -1)
return -1;
if (fBlocking)
fFlags &= ~O_NONBLOCK;
else
fFlags |= O_NONBLOCK;
return -1;
#endif
return 0;
}
#endif
/**
* Internal close function which does all the proper bitching.
*/
{
int rc;
/* ignore nil handles. */
if (Sock == NIL_RTSOCKET)
return VINF_SUCCESS;
/*
* Try to gracefully shut it down.
*/
if (fTryGracefulShutdown)
{
#ifdef FIX_FOR_3_2
#else
if (RT_SUCCESS(rc))
#endif
{
size_t cbReceived = 0;
while ( cbReceived < _1G
{
#ifdef FIX_FOR_3_2
if (rc == 0)
continue;
if (rc < 0)
break;
break;
#else
if (rc == VERR_TIMEOUT)
continue;
if (RT_FAILURE(rc))
break;
if (fEvents & RTSOCKET_EVT_ERROR)
break;
#endif
#ifdef FIX_FOR_3_2
if (cbBytesRead == 0)
break; /* orderly shutdown in progress */
break; /* some kind of error, never mind which... */
#else
if (RT_FAILURE(rc))
break; /* some kind of error, never mind which... */
break; /* orderly shutdown in progress */
#endif
cbReceived += cbRead;
}
}
}
/*
* Close the socket handle (drops our reference to it).
*/
return RTSocketClose(Sock);
}
{
}
{
}
{
int fFlag = 1;
if (RT_SUCCESS(rc))
{
fFlag = 0;
}
return rc;
}
{
}
{
}
{
}
{
}
{
}
{
}
{
return rc;
}
{
}
{
}
RTR3DECL(int) RTTcpWriteNB(RTSOCKET Sock, const void *pvBuffer, size_t cbBuffer, size_t *pcbWritten)
{
}
{
}
{
return rc;
}
{
}