VirtualBox

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

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

Convert to use case-insensitive string compare from runtime.

  • 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
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 BEGING %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(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"), 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, rc, RT_SRC_POS, N_("NAT#%d: configuration query for \"Protocol\" string returned %Vrc"), rc);
338 }
339
340 /* host port */
341 int32_t iHostPort;
342 rc = CFGMR3QueryS32(pNode, "HostPort", &iHostPort);
343 if (VBOX_FAILURE(rc))
344 return PDMDrvHlpVMSetError(pData->pDrvIns, rc, RT_SRC_POS, N_("NAT#%d: configuration query for \"HostPort\" integer returned %Vrc"), rc);
345
346 /* guest port */
347 int32_t iGuestPort;
348 rc = CFGMR3QueryS32(pNode, "GuestPort", &iGuestPort);
349 if (VBOX_FAILURE(rc))
350 return PDMDrvHlpVMSetError(pData->pDrvIns, rc, RT_SRC_POS, N_("NAT#%d: configuration query for \"GuestPort\" integer returned %Vrc"), rc);
351
352 /* guest address */
353 char szGuestIP[32];
354 rc = CFGMR3QueryString(pNode, "GuestIP", &szGuestIP[0], sizeof(szGuestIP));
355 if (rc == VERR_CFGM_VALUE_NOT_FOUND)
356 strcpy(szGuestIP, "10.0.2.15");
357 else if (VBOX_FAILURE(rc))
358 return PDMDrvHlpVMSetError(pData->pDrvIns, rc, RT_SRC_POS, N_("NAT#%d: configuration query for \"GuestIP\" string returned %Vrc"), rc);
359 struct in_addr GuestIP;
360 if (!inet_aton(szGuestIP, &GuestIP))
361 return PDMDrvHlpVMSetError(pData->pDrvIns, VERR_NAT_REDIR_GUEST_IP, RT_SRC_POS, N_("NAT#%d: configuration error: invalid \"GuestIP\"=\"%s\", inet_aton failed"), szGuestIP);
362
363 /*
364 * Call slirp about it.
365 */
366 Log(("drvNATConstruct: Redir %d -> %s:%d\n", iHostPort, szGuestIP, iGuestPort));
367 if (slirp_redir(pData->pNATState, fUDP, iHostPort, GuestIP, iGuestPort) < 0)
368 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);
369 } /* for each redir rule */
370
371 return VINF_SUCCESS;
372}
373
374
375/**
376 * Construct a NAT network transport driver instance.
377 *
378 * @returns VBox status.
379 * @param pDrvIns The driver instance data.
380 * If the registration structure is needed, pDrvIns->pDrvReg points to it.
381 * @param pCfgHandle Configuration node handle for the driver. Use this to obtain the configuration
382 * of the driver instance. It's also found in pDrvIns->pCfgHandle, but like
383 * iInstance it's expected to be used a bit in this function.
384 */
385static DECLCALLBACK(int) drvNATConstruct(PPDMDRVINS pDrvIns, PCFGMNODE pCfgHandle)
386{
387 PDRVNAT pData = PDMINS2DATA(pDrvIns, PDRVNAT);
388 char szNetAddr[16];
389 LogFlow(("drvNATConstruct:\n"));
390
391 /*
392 * Validate the config.
393 */
394 if (!CFGMR3AreValuesValid(pCfgHandle, "\0"))
395 return PDMDRV_SET_ERROR(pDrvIns, VERR_PDM_DRVINS_UNKNOWN_CFG_VALUES, "");
396
397 /*
398 * Init the static parts.
399 */
400 pData->pDrvIns = pDrvIns;
401 pData->pNATState = NULL;
402 /* IBase */
403 pDrvIns->IBase.pfnQueryInterface = drvNATQueryInterface;
404 /* INetwork */
405 pData->INetworkConnector.pfnSend = drvNATSend;
406 pData->INetworkConnector.pfnSetPromiscuousMode = drvNATSetPromiscuousMode;
407 pData->INetworkConnector.pfnNotifyLinkChanged = drvNATNotifyLinkChanged;
408 pData->INetworkConnector.pfnNotifyCanReceive = drvNATNotifyCanReceive;
409
410 /*
411 * Query the network port interface.
412 */
413 pData->pPort = (PPDMINETWORKPORT)pDrvIns->pUpBase->pfnQueryInterface(pDrvIns->pUpBase, PDMINTERFACE_NETWORK_PORT);
414 if (!pData->pPort)
415 return PDMDRV_SET_ERROR(pDrvIns, VERR_PDM_MISSING_INTERFACE_ABOVE,
416 N_("Configuration error: the above device/driver didn't export the network port interface!\n"));
417
418 /* Generate a network address for this network card. */
419 RTStrPrintf(szNetAddr, sizeof(szNetAddr), "10.0.%d.0", pDrvIns->iInstance + 2);
420
421 /*
422 * The slirp lock..
423 */
424 int rc = RTCritSectInit(&pData->CritSect);
425 if (VBOX_FAILURE(rc))
426 return rc;
427#if 0
428 rc = RTSemEventCreate(&g_EventSem);
429 if (VBOX_SUCCESS(rc))
430 {
431 /*
432 * Start the select thread. (it'll block on the sem)
433 */
434 g_fThreadTerm = false;
435 rc = RTThreadCreate(&g_ThreadSelect, drvNATSelectThread, 0, NULL, "NATSEL");
436 if (VBOX_SUCCESS(rc))
437 {
438#endif
439 /*
440 * Initialize slirp.
441 */
442 rc = slirp_init(&pData->pNATState, &szNetAddr[0], pData);
443 if (VBOX_SUCCESS(rc))
444 {
445 rc = drvNATConstructRedir(pData, pCfgHandle);
446 if (VBOX_SUCCESS(rc))
447 {
448 pDrvIns->pDrvHlp->pfnPDMPollerRegister(pDrvIns, drvNATPoller);
449
450 pData->enmLinkState = PDMNETWORKLINKSTATE_UP;
451#if 0
452 RTSemEventSignal(g_EventSem);
453 RTThreadSleep(0);
454#endif
455 return VINF_SUCCESS;
456 }
457 /* failure path */
458 slirp_term(pData->pNATState);
459 pData->pNATState = NULL;
460 }
461 else
462 {
463 switch (rc)
464 {
465 case VERR_NAT_DNS:
466 PDMDRV_SET_ERROR(pDrvIns, rc, N_("Domain Name Server (DNS) for NAT networking could not be determined"));
467 break;
468 default:
469 PDMDRV_SET_ERROR(pDrvIns, rc, N_("Unknown error during NAT networking setup: "));
470 AssertMsgFailed(("Add error message for rc=%d (%Vrc)\n", rc, rc));
471 break;
472 }
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