DrvNAT.cpp revision 640c5443600563afd4f0759c0f0ad4249f065577
/* $Id$ */
/** @file
* DrvNAT - NAT network transport driver.
*/
/*
* Copyright (C) 2006-2009 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.
*
* 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 *
*******************************************************************************/
#define LOG_GROUP LOG_GROUP_DRV_NAT
#define __STDC_LIMIT_MACROS
#define __STDC_CONSTANT_MACROS
#include "Network/slirp/libslirp.h"
#include <iprt/critsect.h>
#include "Builtins.h"
#ifndef RT_OS_WINDOWS
# include <unistd.h>
# include <fcntl.h>
# include <poll.h>
#endif
#include <errno.h>
#include <iprt/semaphore.h>
/*******************************************************************************
* Defined Constants And Macros *
*******************************************************************************/
/**
* @todo: This is a bad hack to prevent freezing the guest during high network
* activity. This needs to be fixed properly.
*/
#define VBOX_NAT_DELAY_HACK
#ifdef VBOX_WITH_STATISTICS
extern "C" void slirp_counting_counter_##name##_add(PNATState pData, int val); /**< @todo r=bird: COUNTING_COUTER is missing an 'N'
and trailing a semicolon. The general idea is that
macros functions should have a trailing semicolon to
make the source easier to parse for doxygen and editors. */
/** @todo think abaout it */
# include "Network/slirp/counters.h"
#else
#endif
/*******************************************************************************
* Structures and Typedefs *
*******************************************************************************/
/**
* NAT network transport driver instance data.
*/
typedef struct DRVNAT
{
/** The network interface. */
/** The port we're attached to. */
/** The network config of the port we're attached to. */
/** Pointer to the driver instance. */
/** Link state */
/** NAT state for this instance. */
/** TFTP directory prefix. */
char *pszTFTPPrefix;
/** Boot file name to provide in the DHCP server response. */
char *pszBootFile;
/** tftp server name to provide in the DHCP server response. */
char *pszNextServer;
/* polling thread */
/** Queue for NAT-thread-external events. */
/* Send queue */
#ifdef VBOX_WITH_SLIRP_MT
#endif
#ifndef RT_OS_WINDOWS
/** The write end of the control pipe. */
/** The read end of the control pipe. */
#else
/** for external notification */
#endif
typedef struct DRVNATQUEUITEM
{
/** The core part owned by the queue manager. */
/** The buffer for output to guest. */
/* size of buffer */
void *mbuf;
/** Converts a pointer to NAT::INetworkConnector to a PRDVNAT. */
#define PDMINETWORKCONNECTOR_2_DRVNAT(pInterface) ( (PDRVNAT)((uintptr_t)pInterface - RT_OFFSETOF(DRVNAT, INetworkConnector)) )
/**
* Worker function for drvNATSend().
* @thread "NAT" thread.
*/
{
}
/**
* Send data to the network.
*
* @returns VBox status code.
* @param pInterface Pointer to the interface structure containing the called function pointer.
* @param pvBuf Data to send.
* @param cb Number of bytes to send.
* @thread EMT
*/
{
int rc;
void *buf;
/* don't queue new requests when the NAT thread is about to stop */
return VINF_SUCCESS;
#ifndef VBOX_WITH_SLIRP_MT
#else
#endif
/* @todo: Here we should get mbuf instead temporal buffer */
{
LogRel(("NAT: Can't allocate send buffer\n"));
return VERR_NO_MEMORY;
}
#ifndef RT_OS_WINDOWS
/* kick select() */
#else
/* kick WSAWaitForMultipleEvents */
#endif
LogFlow(("drvNATSend: end\n"));
return VINF_SUCCESS;
}
/**
* Set promiscuous mode.
*
* This is called when the promiscuous mode is set. This means that there doesn't have
* to be a mode change when it's called.
*
* @param pInterface Pointer to the interface structure containing the called function pointer.
* @param fPromiscuous Set if the adaptor is now in promiscuous mode. Clear if it is not.
* @thread EMT
*/
static DECLCALLBACK(void) drvNATSetPromiscuousMode(PPDMINETWORKCONNECTOR pInterface, bool fPromiscuous)
{
/* nothing to do */
}
/**
* Worker function for drvNATNotifyLinkChanged().
* @thread "NAT" thread.
*/
{
switch (enmLinkState)
{
case PDMNETWORKLINKSTATE_UP:
LogRel(("NAT: link up\n"));
break;
case PDMNETWORKLINKSTATE_DOWN:
LogRel(("NAT: link down\n"));
break;
default:
}
}
/**
* Notification on link status changes.
*
* @param pInterface Pointer to the interface structure containing the called function pointer.
* @param enmLinkState The new link state.
* @thread EMT
*/
static DECLCALLBACK(void) drvNATNotifyLinkChanged(PPDMINETWORKCONNECTOR pInterface, PDMNETWORKLINKSTATE enmLinkState)
{
/* don't queue new requests when the NAT thread is about to stop */
return;
{
#ifndef RT_OS_WINDOWS
/* kick select() */
#else
/* kick WSAWaitForMultipleEvents() */
#endif
}
else
}
{
int nFDs = -1;
unsigned int ms;
#ifdef RT_OS_WINDOWS
unsigned int cBreak = 0;
#else /* RT_OS_WINDOWS */
unsigned int cPollNegRet = 0;
#endif /* !RT_OS_WINDOWS */
return VINF_SUCCESS;
#ifdef RT_OS_WINDOWS
#endif /* RT_OS_WINDOWS */
/*
* Polling loop.
*/
{
nFDs = -1;
/*
*/
#ifndef RT_OS_WINDOWS
/* allocation for all sockets + Management pipe */
return VERR_NO_MEMORY;
/* don't pass the managemant pipe */
/* POLLRDBAND usually doesn't used on Linux but seems used on Solaris */
if (cChangedFDs < 0)
{
{
Log2(("NAT: signal was caught while sleep on poll\n"));
/* No error, just process all outstanding requests but don't wait */
cChangedFDs = 0;
}
else if (cPollNegRet++ > 128)
{
cPollNegRet = 0;
}
}
if (cChangedFDs >= 0)
{
{
/* drain the pipe */
char ch[1];
int counter = 0;
/*
* drvNATSend decoupled so we don't know how many times
* device's thread sends before we've entered multiplex,
* so to avoid false alarm drain pipe here to the very end
*
* @todo: Probably we should counter drvNATSend to count how
* deep pipe has been filed before drain.
*
* XXX:Make it reading exactly we need to drain the pipe.
*/
}
}
/* process _all_ outstanding requests but don't wait */
#else /* RT_OS_WINDOWS */
&& event != WSA_WAIT_TIMEOUT)
{
int error = WSAGetLastError();
}
if (event == WSA_WAIT_TIMEOUT)
{
continue;
}
/* poll the sockets in any case */
/* process _all_ outstanding requests but don't wait */
# ifdef VBOX_NAT_DELAY_HACK
if (cBreak++ > 128)
{
cBreak = 0;
RTThreadSleep(2);
}
# endif
#endif /* RT_OS_WINDOWS */
}
return VINF_SUCCESS;
}
/**
* Unblock the send thread so it can respond to a state change.
*
* @returns VBox status code.
* @param pDevIns The pcnet device instance.
* @param pThread The send thread.
*/
{
#ifndef RT_OS_WINDOWS
/* kick select() */
#else /* !RT_OS_WINDOWS */
/* kick WSAWaitForMultipleEvents() */
#endif /* RT_OS_WINDOWS */
return VINF_SUCCESS;
}
#ifdef VBOX_WITH_SLIRP_MT
{
return VINF_SUCCESS;
{
}
return VINF_SUCCESS;
}
{
return VINF_SUCCESS;
}
#endif /* VBOX_WITH_SLIRP_MT */
/**
* Function called by slirp to check if it's possible to feed incoming data to the network port.
* @returns 1 if possible.
* @returns 0 if not possible.
*/
int slirp_can_output(void *pvUser)
{
return 1;
}
/**
* Function called by slirp to feed incoming data to the network port.
*/
{
if (pItem)
{
return;
}
static unsigned cDroppedPackets;
if (cDroppedPackets < 64)
{
}
else
{
LogRel(("NAT: %d messages suppressed about dropping package (couldn't allocate queue item)\n", cDroppedPackets));
cDroppedPackets = 0;
}
}
/**
* Queue callback for processing a queued item.
*
* @returns Success indicator.
* If false the item will not be removed and the flushing will stop.
* @param pDrvIns The driver instance.
* @param pItemCore Pointer to the queue item to process.
*/
{
if (RT_FAILURE(rc))
return false;
#if 0
#else
/*Copy buffer again, till seeking good way of syncronization with slirp mbuf management code*/
#endif
return RT_SUCCESS(rc);
}
/**
* Queries an interface to the driver.
*
* @returns Pointer to interface.
* @returns NULL if the interface was not supported by the driver.
* @param pInterface Pointer to this interface structure.
* @param enmInterface The requested interface identification.
* @thread Any thread.
*/
{
switch (enmInterface)
{
case PDMINTERFACE_BASE:
return &pThis->INetworkConnector;
default:
return NULL;
}
}
/**
* Destruct a driver instance.
*
* Most VM resources are freed by the VM. This callback is provided so that any non-VM
* resources can be freed correctly.
*
* @param pDrvIns The driver instance data.
*/
{
LogFlow(("drvNATDestruct:\n"));
}
/**
* Sets up the redirectors.
*
* @returns VBox status code.
* @param pCfgHandle The drivers configuration handle.
*/
static int drvNATConstructRedir(unsigned iInstance, PDRVNAT pThis, PCFGMNODE pCfgHandle, RTIPV4ADDR Network)
{
/*
* Enumerate redirections.
*/
{
/*
* Validate the port forwarding config.
*/
return PDMDRV_SET_ERROR(pThis->pDrvIns, VERR_PDM_DRVINS_UNKNOWN_CFG_VALUES, N_("Unknown configuration in port forwarding"));
/* protocol type */
bool fUDP;
char szProtocol[32];
if (rc == VERR_CFGM_VALUE_NOT_FOUND)
{
if (rc == VERR_CFGM_VALUE_NOT_FOUND)
fUDP = false;
else if (RT_FAILURE(rc))
return PDMDrvHlpVMSetError(pThis->pDrvIns, rc, RT_SRC_POS, N_("NAT#%d: configuration query for \"UDP\" boolean failed"), iInstance);
}
else if (RT_SUCCESS(rc))
{
fUDP = false;
fUDP = true;
else
return PDMDrvHlpVMSetError(pThis->pDrvIns, VERR_INVALID_PARAMETER, RT_SRC_POS, N_("NAT#%d: Invalid configuration value for \"Protocol\": \"%s\""), iInstance, szProtocol);
}
else
return PDMDrvHlpVMSetError(pThis->pDrvIns, rc, RT_SRC_POS, N_("NAT#%d: configuration query for \"Protocol\" string failed"), iInstance);
/* host port */
if (RT_FAILURE(rc))
return PDMDrvHlpVMSetError(pThis->pDrvIns, rc, RT_SRC_POS, N_("NAT#%d: configuration query for \"HostPort\" integer failed"), iInstance);
/* guest port */
if (RT_FAILURE(rc))
return PDMDrvHlpVMSetError(pThis->pDrvIns, rc, RT_SRC_POS, N_("NAT#%d: configuration query for \"GuestPort\" integer failed"), iInstance);
/* guest address */
char szGuestIP[32];
if (rc == VERR_CFGM_VALUE_NOT_FOUND)
(Network & 0xFF000000) >> 24, (Network & 0xFF0000) >> 16, (Network & 0xFF00) >> 8, (Network & 0xE0) | 15);
else if (RT_FAILURE(rc))
return PDMDrvHlpVMSetError(pThis->pDrvIns, rc, RT_SRC_POS, N_("NAT#%d: configuration query for \"GuestIP\" string failed"), iInstance);
N_("NAT#%d: configuration error: invalid \"GuestIP\"=\"%s\", inet_aton failed"), iInstance, szGuestIP);
/*
* Call slirp about it.
*/
N_("NAT#%d: configuration error: failed to set up redirection of %d to %s:%d. Probably a conflict with existing services or other rules"), iInstance, iHostPort, szGuestIP, iGuestPort);
} /* for each redir rule */
return VINF_SUCCESS;
}
/**
* Get the MAC address into the slirp stack.
*/
{
{
}
}
/**
* After loading we have to pass the MAC address of the ethernet device to the slirp stack.
* Otherwise the guest is not reachable until it performs a DHCP request or an ARP request
* (usually done during guest boot).
*/
{
return VINF_SUCCESS;
}
/**
* Some guests might not use DHCP to retrieve an IP but use a static IP.
*/
{
}
/**
* Construct a NAT network transport driver instance.
*
* @returns VBox status.
* @param pDrvIns The driver instance data.
* If the registration structure is needed, pDrvIns->pDrvReg points to it.
* @param pCfgHandle Configuration node handle for the driver. Use this to obtain the configuration
* of the driver instance. It's also found in pDrvIns->pCfgHandle, but like
* iInstance it's expected to be used a bit in this function.
*/
{
char szNetAddr[16];
LogFlow(("drvNATConstruct:\n"));
/*
* Validate the config.
*/
#ifdef VBOX_WITH_SLIRP_DNS_PROXY
"DNSProxy\0"
#endif
"SocketRcvBuf\0SocketSndBuf\0TcpRcvSpace\0TcpSndSpace\0"))
N_("Unknown NAT configuration option, only supports PassDomain, TFTPPrefix, BootFile and Network"));
/*
* Init the static parts.
*/
/* IBase */
/* INetwork */
/*
* Get the configuration settings.
*/
bool fPassDomain = true;
if (rc == VERR_CFGM_VALUE_NOT_FOUND)
fPassDomain = true;
else if (RT_FAILURE(rc))
return PDMDrvHlpVMSetError(pDrvIns, rc, RT_SRC_POS, N_("NAT#%d: configuration query for \"PassDomain\" boolean failed"), pDrvIns->iInstance);
return PDMDrvHlpVMSetError(pDrvIns, rc, RT_SRC_POS, N_("NAT#%d: configuration query for \"TFTPPrefix\" string failed"), pDrvIns->iInstance);
return PDMDrvHlpVMSetError(pDrvIns, rc, RT_SRC_POS, N_("NAT#%d: configuration query for \"BootFile\" string failed"), pDrvIns->iInstance);
return PDMDrvHlpVMSetError(pDrvIns, rc, RT_SRC_POS, N_("NAT#%d: configuration query for \"NextServer\" string failed"), pDrvIns->iInstance);
#ifdef VBOX_WITH_SLIRP_DNS_PROXY
int fDNSProxy;
if (rc == VERR_CFGM_VALUE_NOT_FOUND)
fDNSProxy = 0;
#endif
/*
* Query the network port interface.
*/
pThis->pPort = (PPDMINETWORKPORT)pDrvIns->pUpBase->pfnQueryInterface(pDrvIns->pUpBase, PDMINTERFACE_NETWORK_PORT);
pThis->pConfig = (PPDMINETWORKCONFIG)pDrvIns->pUpBase->pfnQueryInterface(pDrvIns->pUpBase, PDMINTERFACE_NETWORK_CONFIG);
/* Generate a network address for this network card. */
if (rc == VERR_CFGM_VALUE_NOT_FOUND)
else if (RT_FAILURE(rc))
return PDMDrvHlpVMSetError(pDrvIns, rc, RT_SRC_POS, N_("NAT#%d: configuration query for \"Network\" string failed"), pDrvIns->iInstance);
if (RT_FAILURE(rc))
return PDMDrvHlpVMSetError(pDrvIns, rc, RT_SRC_POS, N_("NAT#%d: Configuration error: network '%s' describes not a valid IPv4 network"), pDrvIns->iInstance, szNetwork);
/*
* Initialize slirp.
*/
if (RT_SUCCESS(rc))
{
#ifdef VBOX_WITH_SLIRP_DNS_PROXY
#endif
do \
{ \
int len = 0; \
if (RT_SUCCESS(rc)) \
}while(0)
if (RT_SUCCESS(rc2))
{
/*
* Register a load done notification to get the MAC address into the slirp
* engine after we loaded a guest state.
*/
if (RT_FAILURE(rc))
{
LogRel(("NAT: Can't create request queue\n"));
return rc;
}
rc = PDMDrvHlpPDMQueueCreate(pDrvIns, sizeof(DRVNATQUEUITEM), 50, 0, drvNATQueueConsumer, &pThis->pSendQueue);
if (RT_FAILURE(rc))
{
LogRel(("NAT: Can't create send queue\n"));
return rc;
}
#ifndef RT_OS_WINDOWS
/*
* Create the control pipe.
*/
int fds[2];
{
return rc;
}
#else
#endif
rc = PDMDrvHlpPDMThreadCreate(pDrvIns, &pThis->pThread, pThis, drvNATAsyncIoThread, drvNATAsyncIoWakeup, 128 * _1K, RTTHREADTYPE_IO, "NAT");
#ifdef VBOX_WITH_SLIRP_MT
rc = PDMDrvHlpPDMThreadCreate(pDrvIns, &pThis->pGuestThread, pThis, drvNATAsyncIoGuest, drvNATAsyncIoGuestWakeup, 128 * _1K, RTTHREADTYPE_IO, "NATGUEST");
#endif
/* might return VINF_NAT_DNS */
return rc;
}
/* failure path */
}
else
{
}
return rc;
}
/**
* NAT network transport driver registration record.
*/
{
/* u32Version */
/* szDriverName */
"NAT",
/* pszDescription */
"NAT Network Transport Driver",
/* fFlags */
/* fClass. */
/* cMaxInstances */
16,
/* cbInstance */
sizeof(DRVNAT),
/* pfnConstruct */
/* pfnDestruct */
/* pfnIOCtl */
NULL,
/* pfnPowerOn */
/* pfnReset */
NULL,
/* pfnSuspend */
NULL,
/* pfnResume */
NULL,
/* pfnDetach */
NULL,
/* pfnPowerOff */
};