VirtualBox

source: vbox/trunk/src/VBox/Devices/Network/DrvNAT.cpp@ 3670

Last change on this file since 3670 was 2981, checked in by vboxsync, 17 years ago

InnoTek -> innotek: all the headers and comments.

  • Property svn:eol-style set to native
  • Property svn:keywords set to Author Date Id Revision
File size: 17.2 KB
Line 
1/** @file
2 *
3 * VBox network devices:
4 * NAT network transport driver
5 */
6
7/*
8 * Copyright (C) 2006-2007 innotek GmbH
9 *
10 * This file is part of VirtualBox Open Source Edition (OSE), as
11 * available from http://www.virtualbox.org. This file is free software;
12 * you can redistribute it and/or modify it under the terms of the GNU
13 * General Public License as published by the Free Software Foundation,
14 * in version 2 as it comes in the "COPYING" file of the VirtualBox OSE
15 * distribution. VirtualBox OSE is distributed in the hope that it will
16 * be useful, but WITHOUT ANY WARRANTY of any kind.
17 *
18 * If you received this file as part of a commercial VirtualBox
19 * distribution, then only the terms of your commercial VirtualBox
20 * license agreement apply instead of the previous paragraph.
21 */
22
23
24/*******************************************************************************
25* Header Files *
26*******************************************************************************/
27#define LOG_GROUP LOG_GROUP_DRV_NAT
28#include "Network/slirp/libslirp.h"
29#include <VBox/pdm.h>
30#include <VBox/cfgm.h>
31#include <VBox/mm.h>
32#include <VBox/err.h>
33
34#include <VBox/log.h>
35#include <iprt/assert.h>
36#include <iprt/file.h>
37#include <iprt/string.h>
38#include <iprt/critsect.h>
39
40#include "Builtins.h"
41
42
43/*******************************************************************************
44* Structures and Typedefs *
45*******************************************************************************/
46/**
47 * Block driver instance data.
48 */
49typedef struct DRVNAT
50{
51 /** The network interface. */
52 PDMINETWORKCONNECTOR INetworkConnector;
53 /** The port we're attached to. */
54 PPDMINETWORKPORT pPort;
55 /** Pointer to the driver instance. */
56 PPDMDRVINS pDrvIns;
57 /** Slirp critical section. */
58 RTCRITSECT CritSect;
59 /** Link state */
60 PDMNETWORKLINKSTATE enmLinkState;
61 /** NAT state for this instance. */
62 PNATState pNATState;
63} DRVNAT, *PDRVNAT;
64
65/** Converts a pointer to NAT::INetworkConnector to a PRDVNAT. */
66#define PDMINETWORKCONNECTOR_2_DRVNAT(pInterface) ( (PDRVNAT)((uintptr_t)pInterface - RT_OFFSETOF(DRVNAT, INetworkConnector)) )
67
68
69/*******************************************************************************
70* Global Variables *
71*******************************************************************************/
72#if 0
73/** If set the thread should terminate. */
74static bool g_fThreadTerm = false;
75/** The thread id of the select thread (drvNATSelectThread()). */
76static RTTHREAD g_ThreadSelect;
77#endif
78
79
80/**
81 * Send data to the network.
82 *
83 * @returns VBox status code.
84 * @param pInterface Pointer to the interface structure containing the called function pointer.
85 * @param pvBuf Data to send.
86 * @param cb Number of bytes to send.
87 * @thread EMT
88 */
89static DECLCALLBACK(int) drvNATSend(PPDMINETWORKCONNECTOR pInterface, const void *pvBuf, size_t cb)
90{
91 PDRVNAT pData = PDMINETWORKCONNECTOR_2_DRVNAT(pInterface);
92
93 LogFlow(("drvNATSend: pvBuf=%p cb=%#x\n", pvBuf, cb));
94 Log2(("drvNATSend: pvBuf=%p cb=%#x\n"
95 "%.*Vhxd\n",
96 pvBuf, cb, cb, pvBuf));
97
98 int rc = RTCritSectEnter(&pData->CritSect);
99 AssertReleaseRC(rc);
100
101 Assert(pData->enmLinkState == PDMNETWORKLINKSTATE_UP);
102 if (pData->enmLinkState == PDMNETWORKLINKSTATE_UP)
103 slirp_input(pData->pNATState, (uint8_t *)pvBuf, cb);
104 RTCritSectLeave(&pData->CritSect);
105 LogFlow(("drvNATSend: end\n"));
106 return VINF_SUCCESS;
107}
108
109
110/**
111 * Set promiscuous mode.
112 *
113 * This is called when the promiscuous mode is set. This means that there doesn't have
114 * to be a mode change when it's called.
115 *
116 * @param pInterface Pointer to the interface structure containing the called function pointer.
117 * @param fPromiscuous Set if the adaptor is now in promiscuous mode. Clear if it is not.
118 * @thread EMT
119 */
120static DECLCALLBACK(void) drvNATSetPromiscuousMode(PPDMINETWORKCONNECTOR pInterface, bool fPromiscuous)
121{
122 LogFlow(("drvNATSetPromiscuousMode: fPromiscuous=%d\n", fPromiscuous));
123 /* nothing to do */
124}
125
126
127/**
128 * Notification on link status changes.
129 *
130 * @param pInterface Pointer to the interface structure containing the called function pointer.
131 * @param enmLinkState The new link state.
132 * @thread EMT
133 */
134static DECLCALLBACK(void) drvNATNotifyLinkChanged(PPDMINETWORKCONNECTOR pInterface, PDMNETWORKLINKSTATE enmLinkState)
135{
136 PDRVNAT pData = PDMINETWORKCONNECTOR_2_DRVNAT(pInterface);
137
138 LogFlow(("drvNATNotifyLinkChanged: enmLinkState=%d\n", enmLinkState));
139
140 int rc = RTCritSectEnter(&pData->CritSect);
141 AssertReleaseRC(rc);
142 pData->enmLinkState = enmLinkState;
143
144 switch (enmLinkState)
145 {
146 case PDMNETWORKLINKSTATE_UP:
147 LogRel(("NAT: link up\n"));
148 slirp_link_up(pData->pNATState);
149 break;
150
151 case PDMNETWORKLINKSTATE_DOWN:
152 case PDMNETWORKLINKSTATE_DOWN_RESUME:
153 LogRel(("NAT: link down\n"));
154 slirp_link_down(pData->pNATState);
155 break;
156
157 default:
158 AssertMsgFailed(("drvNATNotifyLinkChanged: unexpected link state %d\n", enmLinkState));
159 }
160 RTCritSectLeave(&pData->CritSect);
161}
162
163
164/**
165 * More receive buffer has become available.
166 *
167 * This is called when the NIC frees up receive buffers.
168 *
169 * @param pInterface Pointer to the interface structure containing the called function pointer.
170 * @thread EMT
171 */
172static DECLCALLBACK(void) drvNATNotifyCanReceive(PPDMINETWORKCONNECTOR pInterface)
173{
174 LogFlow(("drvNATNotifyCanReceive:\n"));
175 /** @todo do something useful here. */
176}
177
178
179/**
180 * Poller callback.
181 */
182static DECLCALLBACK(void) drvNATPoller(PPDMDRVINS pDrvIns)
183{
184 PDRVNAT pData = PDMINS2DATA(pDrvIns, PDRVNAT);
185 fd_set ReadFDs;
186 fd_set WriteFDs;
187 fd_set XcptFDs;
188 int cFDs = -1;
189 FD_ZERO(&ReadFDs);
190 FD_ZERO(&WriteFDs);
191 FD_ZERO(&XcptFDs);
192
193 int rc = RTCritSectEnter(&pData->CritSect);
194 AssertReleaseRC(rc);
195
196 slirp_select_fill(pData->pNATState, &cFDs, &ReadFDs, &WriteFDs, &XcptFDs);
197
198 struct timeval tv = {0, 0}; /* no wait */
199 int cReadFDs = select(cFDs + 1, &ReadFDs, &WriteFDs, &XcptFDs, &tv);
200 if (cReadFDs >= 0)
201 slirp_select_poll(pData->pNATState, &ReadFDs, &WriteFDs, &XcptFDs);
202
203 RTCritSectLeave(&pData->CritSect);
204}
205
206
207/**
208 * Function called by slirp to check if it's possible to feed incoming data to the network port.
209 * @returns 1 if possible.
210 * @returns 0 if not possible.
211 */
212int slirp_can_output(void *pvUser)
213{
214 PDRVNAT pData = (PDRVNAT)pvUser;
215
216 Assert(pData);
217
218 /** Happens during termination */
219 if (!RTCritSectIsOwner(&pData->CritSect))
220 return 0;
221
222 return pData->pPort->pfnCanReceive(pData->pPort);
223}
224
225
226/**
227 * Function called by slirp to feed incoming data to the network port.
228 */
229void slirp_output(void *pvUser, const uint8_t *pu8Buf, int cb)
230{
231 PDRVNAT pData = (PDRVNAT)pvUser;
232
233 LogFlow(("slirp_output BEGIN %x %d\n", pu8Buf, cb));
234 Log2(("slirp_output: pu8Buf=%p cb=%#x (pData=%p)\n"
235 "%.*Vhxd\n",
236 pu8Buf, cb, pData,
237 cb, pu8Buf));
238
239 Assert(pData);
240
241 /** Happens during termination */
242 if (!RTCritSectIsOwner(&pData->CritSect))
243 return;
244
245 int rc = pData->pPort->pfnReceive(pData->pPort, pu8Buf, cb);
246 AssertRC(rc);
247 LogFlow(("slirp_output END %x %d\n", pu8Buf, cb));
248}
249
250/**
251 * Queries an interface to the driver.
252 *
253 * @returns Pointer to interface.
254 * @returns NULL if the interface was not supported by the driver.
255 * @param pInterface Pointer to this interface structure.
256 * @param enmInterface The requested interface identification.
257 * @thread Any thread.
258 */
259static DECLCALLBACK(void *) drvNATQueryInterface(PPDMIBASE pInterface, PDMINTERFACE enmInterface)
260{
261 PPDMDRVINS pDrvIns = PDMIBASE_2_PDMDRV(pInterface);
262 PDRVNAT pData = PDMINS2DATA(pDrvIns, PDRVNAT);
263 switch (enmInterface)
264 {
265 case PDMINTERFACE_BASE:
266 return &pDrvIns->IBase;
267 case PDMINTERFACE_NETWORK_CONNECTOR:
268 return &pData->INetworkConnector;
269 default:
270 return NULL;
271 }
272}
273
274
275/**
276 * Destruct a driver instance.
277 *
278 * Most VM resources are freed by the VM. This callback is provided so that any non-VM
279 * resources can be freed correctly.
280 *
281 * @param pDrvIns The driver instance data.
282 */
283static DECLCALLBACK(void) drvNATDestruct(PPDMDRVINS pDrvIns)
284{
285 PDRVNAT pData = PDMINS2DATA(pDrvIns, PDRVNAT);
286
287 LogFlow(("drvNATDestruct:\n"));
288
289 int rc = RTCritSectEnter(&pData->CritSect);
290 AssertReleaseRC(rc);
291 slirp_term(pData->pNATState);
292 pData->pNATState = NULL;
293 RTCritSectLeave(&pData->CritSect);
294
295 RTCritSectDelete(&pData->CritSect);
296}
297
298
299/**
300 * Sets up the redirectors.
301 *
302 * @returns VBox status code.
303 * @param pCfgHandle The drivers configuration handle.
304 */
305static int drvNATConstructRedir(unsigned iInstance, PDRVNAT pData, PCFGMNODE pCfgHandle)
306{
307 /*
308 * Enumerate redirections.
309 */
310 for (PCFGMNODE pNode = CFGMR3GetFirstChild(pCfgHandle); pNode; pNode = CFGMR3GetNextChild(pNode))
311 {
312 /*
313 * Validate the port forwarding config.
314 */
315 if (!CFGMR3AreValuesValid(pNode, "Protocol\0UDP\0HostPort\0GuestPort\0GuestIP\0"))
316 return PDMDRV_SET_ERROR(pData->pDrvIns, VERR_PDM_DRVINS_UNKNOWN_CFG_VALUES, N_("Unknown configuration in port forwarding"));
317
318 /* protocol type */
319 bool fUDP;
320 char szProtocol[32];
321 int rc = CFGMR3QueryString(pNode, "Protocol", &szProtocol[0], sizeof(szProtocol));
322 if (rc == VERR_CFGM_VALUE_NOT_FOUND)
323 {
324 rc = CFGMR3QueryBool(pNode, "UDP", &fUDP);
325 if (rc == VERR_CFGM_VALUE_NOT_FOUND)
326 fUDP = false;
327 else if (VBOX_FAILURE(rc))
328 return PDMDrvHlpVMSetError(pData->pDrvIns, rc, RT_SRC_POS, N_("NAT#%d: configuration query for \"UDP\" boolean returned %Vrc"), iInstance, rc);
329 }
330 else if (VBOX_SUCCESS(rc))
331 {
332 if (!RTStrICmp(szProtocol, "TCP"))
333 fUDP = false;
334 else if (!RTStrICmp(szProtocol, "UDP"))
335 fUDP = true;
336 else
337 return PDMDrvHlpVMSetError(pData->pDrvIns, VERR_INVALID_PARAMETER, RT_SRC_POS, N_("NAT#%d: Invalid configuration value for \"Protocol\": \"%s\""), iInstance, szProtocol);
338 }
339 else
340 return PDMDrvHlpVMSetError(pData->pDrvIns, rc, RT_SRC_POS, N_("NAT#%d: configuration query for \"Protocol\" string returned %Vrc"), iInstance, rc);
341
342 /* host port */
343 int32_t iHostPort;
344 rc = CFGMR3QueryS32(pNode, "HostPort", &iHostPort);
345 if (VBOX_FAILURE(rc))
346 return PDMDrvHlpVMSetError(pData->pDrvIns, rc, RT_SRC_POS, N_("NAT#%d: configuration query for \"HostPort\" integer returned %Vrc"), iInstance, rc);
347
348 /* guest port */
349 int32_t iGuestPort;
350 rc = CFGMR3QueryS32(pNode, "GuestPort", &iGuestPort);
351 if (VBOX_FAILURE(rc))
352 return PDMDrvHlpVMSetError(pData->pDrvIns, rc, RT_SRC_POS, N_("NAT#%d: configuration query for \"GuestPort\" integer returned %Vrc"), iInstance, rc);
353
354 /* guest address */
355 char szGuestIP[32];
356 rc = CFGMR3QueryString(pNode, "GuestIP", &szGuestIP[0], sizeof(szGuestIP));
357 if (rc == VERR_CFGM_VALUE_NOT_FOUND)
358 strcpy(szGuestIP, "10.0.2.15");
359 else if (VBOX_FAILURE(rc))
360 return PDMDrvHlpVMSetError(pData->pDrvIns, rc, RT_SRC_POS, N_("NAT#%d: configuration query for \"GuestIP\" string returned %Vrc"), iInstance, rc);
361 struct in_addr GuestIP;
362 if (!inet_aton(szGuestIP, &GuestIP))
363 return PDMDrvHlpVMSetError(pData->pDrvIns, VERR_NAT_REDIR_GUEST_IP, RT_SRC_POS, N_("NAT#%d: configuration error: invalid \"GuestIP\"=\"%s\", inet_aton failed"), iInstance, szGuestIP);
364
365 /*
366 * Call slirp about it.
367 */
368 Log(("drvNATConstruct: Redir %d -> %s:%d\n", iHostPort, szGuestIP, iGuestPort));
369 if (slirp_redir(pData->pNATState, fUDP, iHostPort, GuestIP, iGuestPort) < 0)
370 return PDMDrvHlpVMSetError(pData->pDrvIns, VERR_NAT_REDIR_SETUP, RT_SRC_POS, 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);
371 } /* for each redir rule */
372
373 return VINF_SUCCESS;
374}
375
376
377/**
378 * Construct a NAT network transport driver instance.
379 *
380 * @returns VBox status.
381 * @param pDrvIns The driver instance data.
382 * If the registration structure is needed, pDrvIns->pDrvReg points to it.
383 * @param pCfgHandle Configuration node handle for the driver. Use this to obtain the configuration
384 * of the driver instance. It's also found in pDrvIns->pCfgHandle, but like
385 * iInstance it's expected to be used a bit in this function.
386 */
387static DECLCALLBACK(int) drvNATConstruct(PPDMDRVINS pDrvIns, PCFGMNODE pCfgHandle)
388{
389 PDRVNAT pData = PDMINS2DATA(pDrvIns, PDRVNAT);
390 char szNetAddr[16];
391 LogFlow(("drvNATConstruct:\n"));
392
393 /*
394 * Validate the config.
395 */
396 if (!CFGMR3AreValuesValid(pCfgHandle, "PassDomain\0"))
397 return PDMDRV_SET_ERROR(pDrvIns, VERR_PDM_DRVINS_UNKNOWN_CFG_VALUES, "Unknown NAT configuration option, only supports PassDomain");
398
399 /*
400 * Get the configuration settings.
401 */
402 bool fPassDomain = true;
403 int rc = CFGMR3QueryBool(pCfgHandle, "PassDomain", &fPassDomain);
404 if (rc == VERR_CFGM_VALUE_NOT_FOUND)
405 fPassDomain = true;
406 else if (VBOX_FAILURE(rc))
407 return PDMDrvHlpVMSetError(pData->pDrvIns, rc, RT_SRC_POS, N_("NAT#%d: configuration query for \"PassDomain\" boolean returned %Vrc"), pDrvIns->iInstance, rc);
408
409 /*
410 * Init the static parts.
411 */
412 pData->pDrvIns = pDrvIns;
413 pData->pNATState = NULL;
414 /* IBase */
415 pDrvIns->IBase.pfnQueryInterface = drvNATQueryInterface;
416 /* INetwork */
417 pData->INetworkConnector.pfnSend = drvNATSend;
418 pData->INetworkConnector.pfnSetPromiscuousMode = drvNATSetPromiscuousMode;
419 pData->INetworkConnector.pfnNotifyLinkChanged = drvNATNotifyLinkChanged;
420 pData->INetworkConnector.pfnNotifyCanReceive = drvNATNotifyCanReceive;
421
422 /*
423 * Query the network port interface.
424 */
425 pData->pPort = (PPDMINETWORKPORT)pDrvIns->pUpBase->pfnQueryInterface(pDrvIns->pUpBase, PDMINTERFACE_NETWORK_PORT);
426 if (!pData->pPort)
427 return PDMDRV_SET_ERROR(pDrvIns, VERR_PDM_MISSING_INTERFACE_ABOVE,
428 N_("Configuration error: the above device/driver didn't export the network port interface!\n"));
429
430 /* Generate a network address for this network card. */
431 RTStrPrintf(szNetAddr, sizeof(szNetAddr), "10.0.%d.0", pDrvIns->iInstance + 2);
432
433 /*
434 * The slirp lock..
435 */
436 rc = RTCritSectInit(&pData->CritSect);
437 if (VBOX_FAILURE(rc))
438 return rc;
439#if 0
440 rc = RTSemEventCreate(&g_EventSem);
441 if (VBOX_SUCCESS(rc))
442 {
443 /*
444 * Start the select thread. (it'll block on the sem)
445 */
446 g_fThreadTerm = false;
447 rc = RTThreadCreate(&g_ThreadSelect, drvNATSelectThread, 0, NULL, "NATSEL");
448 if (VBOX_SUCCESS(rc))
449 {
450#endif
451 /*
452 * Initialize slirp.
453 */
454 rc = slirp_init(&pData->pNATState, &szNetAddr[0], fPassDomain, pData);
455 if (VBOX_SUCCESS(rc))
456 {
457 int rc2 = drvNATConstructRedir(pDrvIns->iInstance, pData, pCfgHandle);
458 if (VBOX_SUCCESS(rc2))
459 {
460 pDrvIns->pDrvHlp->pfnPDMPollerRegister(pDrvIns, drvNATPoller);
461
462 pData->enmLinkState = PDMNETWORKLINKSTATE_UP;
463#if 0
464 RTSemEventSignal(g_EventSem);
465 RTThreadSleep(0);
466#endif
467 /* might return VINF_NAT_DNS */
468 return rc;
469 }
470 /* failure path */
471 slirp_term(pData->pNATState);
472 pData->pNATState = NULL;
473 }
474 else
475 {
476 PDMDRV_SET_ERROR(pDrvIns, rc, N_("Unknown error during NAT networking setup: "));
477 AssertMsgFailed(("Add error message for rc=%d (%Vrc)\n", rc, rc));
478 }
479#if 0
480 g_fThreadTerm = true;
481 RTSemEventSignal(g_EventSem);
482 RTThreadSleep(0);
483 }
484 RTSemEventDestroy(g_EventSem);
485 g_EventSem = NULL;
486 }
487#endif
488 RTCritSectDelete(&pData->CritSect);
489 return rc;
490}
491
492
493
494/**
495 * NAT network transport driver registration record.
496 */
497const PDMDRVREG g_DrvNAT =
498{
499 /* u32Version */
500 PDM_DRVREG_VERSION,
501 /* szDriverName */
502 "NAT",
503 /* pszDescription */
504 "NAT Network Transport Driver",
505 /* fFlags */
506 PDM_DRVREG_FLAGS_HOST_BITS_DEFAULT,
507 /* fClass. */
508 PDM_DRVREG_CLASS_NETWORK,
509 /* cMaxInstances */
510 16,
511 /* cbInstance */
512 sizeof(DRVNAT),
513 /* pfnConstruct */
514 drvNATConstruct,
515 /* pfnDestruct */
516 drvNATDestruct,
517 /* pfnIOCtl */
518 NULL,
519 /* pfnPowerOn */
520 NULL,
521 /* pfnReset */
522 NULL,
523 /* pfnSuspend */
524 NULL,
525 /* pfnResume */
526 NULL,
527 /* pfnDetach */
528 NULL,
529 /* pfnPowerOff */
530 NULL
531};
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