VirtualBox

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

Last change on this file since 1878 was 1878, checked in by vboxsync, 18 years ago

removed RTPrintf

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

© 2025 Oracle Support Privacy / Do Not Sell My Info Terms of Use Trademark Policy Automated Access Etiquette