VirtualBox

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

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

Typo.

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