tcp.cpp revision c3f4feb17e80571ab4978271986932211a3514b5
/* $Id$ */
/** @file
*/
/*
* Copyright (C) 2006-2007 Sun Microsystems, Inc.
*
* 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.
*
* Please contact Sun Microsystems, Inc., 4150 Network Circle, Santa
* Clara, CA 95054 USA or visit http://www.sun.com if you need
* additional information or have any questions.
*/
/*******************************************************************************
* Header Files *
*******************************************************************************/
#ifdef RT_OS_WINDOWS
# include <winsock.h>
# include <limits.h>
#else /* !RT_OS_WINDOWS */
# include <errno.h>
# ifdef IPRT_WITH_TCPIP_V6
# endif
# include <netdb.h>
# include <unistd.h>
#endif /* !RT_OS_WINDOWS */
/*******************************************************************************
* 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 SockServer;
/** The socket to the client currently being serviced.
* This is NIL_RTSOCKET when no client is serviced. */
RTSOCKET volatile SockClient;
/** The connection function. */
/** Argument to pfnServer. */
void *pvUser;
} RTTCPSERVER;
/*******************************************************************************
* Internal Functions *
*******************************************************************************/
/**
* Get the last error as an iprt status code.
*
* @returns iprt status code.
*/
DECLINLINE(int) rtTcpError(void)
{
#ifdef RT_OS_WINDOWS
return RTErrConvertFromWin32(WSAGetLastError());
#else
return RTErrConvertFromErrno(errno);
#endif
}
/**
* Resets the last error.
*/
DECLINLINE(void) rtTcpErrorReset(void)
{
#ifdef RT_OS_WINDOWS
WSASetLastError(0);
#else
errno = 0;
#endif
}
/**
* Get the last resolver error as an iprt status code.
*
* @returns iprt status code.
*/
DECLINLINE(int) rtTcpResolverError(void)
{
#ifdef RT_OS_WINDOWS
return RTErrConvertFromWin32(WSAGetLastError());
#else
switch (h_errno)
{
case HOST_NOT_FOUND:
return VERR_NET_HOST_NOT_FOUND;
case NO_DATA:
return VERR_NET_ADDRESS_NOT_AVAILABLE;
case NO_RECOVERY:
return VERR_IO_GEN_FAILURE;
case TRY_AGAIN:
return VERR_TRY_AGAIN;
default:
return VERR_UNRESOLVED_ERROR;
}
#endif
}
/**
* Atomicly updates a socket variable.
* @returns The old value.
* @param pSock The socket variable to update.
* @param Sock The new value.
*/
{
switch (sizeof(RTSOCKET))
{
default:
return NIL_RTSOCKET;
}
}
/**
* 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 (Sock != 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 = rtTcpResolverError();
return rc;
}
}
}
/*
* Setting up socket.
*/
if (WaitSock != -1)
{
/*
* 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.
*/
{
/*
* Listen for connections on a socket.
*/
{
/*
* Create the server handle.
*/
if (pServer)
{
return VINF_SUCCESS;
}
/* bail out */
rc = VERR_NO_MEMORY;
}
else
{
rc = rtTcpError();
}
}
else
{
rc = rtTcpError();
}
}
else
{
rc = rtTcpError();
}
}
else
{
rc = rtTcpError();
}
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.
*/
if ( enmState != RTTCPSERVERSTATE_ACCEPTING
&& enmState != RTTCPSERVERSTATE_SERVING)
return rcTcpServerListenCleanup(pServer);
continue;
/*
* Accept connection.
*/
struct sockaddr_in RemoteAddr;
if (Socket == -1)
{
#ifndef RT_OS_WINDOWS
/* These are typical for what can happen during destruction. */
return rcTcpServerListenCleanup(pServer);
#endif
continue;
}
/*
* Run a pfnServe callback.
*/
{
return rcTcpServerListenCleanup(pServer);
}
/*
* 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:
}
}
/**
* 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->SockClient, "DisconnectClient: client", true /*fTryGracefulShutdown*/);
return rc;
}
/**
* 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->SockServer, "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->SockServer, "Destroyer: server", false /*fTryGracefulShutdown*/);
/*
* Release it.
*/
return VINF_SUCCESS;
}
{
/*
* Validate input.
*/
/*
* Read loop.
* If pcbRead is NULL we have to fill the entire buffer!
*/
for (;;)
{
#ifdef RT_OS_WINDOWS
#else
#endif
if (cbBytesRead <= 0)
{
int rc = rtTcpError();
if (RT_FAILURE_NP(rc))
return rc;
if (pcbRead)
{
*pcbRead = 0;
return VINF_SUCCESS;
}
return VERR_NET_SHUTDOWN;
}
if (pcbRead)
{
/* return partial data */
*pcbRead = cbBytesRead;
break;
}
/* read more? */
cbRead += cbBytesRead;
break;
/* next */
}
return VINF_SUCCESS;
}
{
do
{
#ifdef RT_OS_WINDOWS
#else
#endif
if (cbWritten < 0)
return rtTcpError();
AssertMsg(cbBuffer >= (size_t)cbWritten, ("Wrote more than we requested!!! cbWritten=%d cbBuffer=%d rtTcpError()=%d\n",
} while (cbBuffer);
return VINF_SUCCESS;
}
{
int fFlag = 1;
fFlag = 0;
return VINF_SUCCESS;
}
{
int rc;
if (cMillies == RT_INDEFINITE_WAIT)
else
{
}
if (rc > 0)
return VINF_SUCCESS;
if (rc == 0)
return VERR_TIMEOUT;
return rtTcpError();
}
{
union
{
struct sockaddr_in Ipv4;
#ifdef IPRT_WITH_TCPIP_V6
struct sockaddr_in6 Ipv6;
#endif
} u;
#ifdef RT_OS_WINDOWS
int cbAddr = sizeof(u);
#else
#endif
RT_ZERO(u);
{
/*
* Convert the address.
*/
if ( cbAddr == sizeof(struct sockaddr_in)
{
}
#ifdef IPRT_WITH_TCPIP_V6
else if ( cbAddr == sizeof(struct sockaddr_in6)
{
}
#endif
else
return VINF_SUCCESS;
}
return rtTcpError();
}
{
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 = rtTcpError();
return rc;
}
}
/*
* Create the socket and connect.
*/
if (Sock != -1)
{
struct sockaddr_in InAddr;
{
return VINF_SUCCESS;
}
rc = rtTcpError();
}
else
rc = rtTcpError();
return rc;
}
{
}
/**
* 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)
{
if (!rc)
{
for (;;)
{
if (rc == VERR_TIMEOUT)
{
break;
}
else if (rc != VINF_SUCCESS)
break;
{
if (cbBytesRead == 0)
break; /* orderly shutdown in progress */
if (cbBytesRead < 0)
break; /* some kind of error, never mind which... */
}
} /* forever */
}
}
/*
* Attempt to close it.
*/
#ifdef RT_OS_WINDOWS
#else
#endif
if (!rc)
return VINF_SUCCESS;
rc = rtTcpError();
return rc;
}