VirtualBox

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

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

Use pdmdrv.h and pdmdev.h where appropirate.

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