VirtualBox

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

Last change on this file since 19722 was 19074, checked in by vboxsync, 16 years ago

DrvNAT: spelling.

  • Property svn:eol-style set to native
  • Property svn:keywords set to Author Date Id Revision
File size: 31.6 KB
Line 
1/** @file
2 *
3 * VBox network devices:
4 * NAT network transport driver
5 */
6
7/*
8 * Copyright (C) 2006-2007 Sun Microsystems, Inc.
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 (GPL) as published by the Free Software
14 * Foundation, in version 2 as it comes in the "COPYING" file of the
15 * VirtualBox OSE distribution. VirtualBox OSE is distributed in the
16 * hope that it will be useful, but WITHOUT ANY WARRANTY of any kind.
17 *
18 * Please contact Sun Microsystems, Inc., 4150 Network Circle, Santa
19 * Clara, CA 95054 USA or visit http://www.sun.com if you need
20 * additional information or have any questions.
21 */
22
23
24/*******************************************************************************
25* Header Files *
26*******************************************************************************/
27#define LOG_GROUP LOG_GROUP_DRV_NAT
28#define __STDC_LIMIT_MACROS
29#define __STDC_CONSTANT_MACROS
30#include "Network/slirp/libslirp.h"
31#include <VBox/pdmdrv.h>
32#include <iprt/assert.h>
33#include <iprt/file.h>
34#include <iprt/mem.h>
35#include <iprt/string.h>
36#include <iprt/critsect.h>
37#include <iprt/cidr.h>
38#include <iprt/stream.h>
39
40#include "Builtins.h"
41
42#ifndef RT_OS_WINDOWS
43# include <unistd.h>
44# include <fcntl.h>
45# include <poll.h>
46#endif
47#include <errno.h>
48#include <iprt/semaphore.h>
49#include <iprt/req.h>
50
51/**
52 * @todo: This is a bad hack to prevent freezing the guest during high network
53 * activity. This needs to be fixed properly.
54 */
55#define VBOX_NAT_DELAY_HACK
56
57
58/*******************************************************************************
59* Structures and Typedefs *
60*******************************************************************************/
61/**
62 * NAT network transport driver instance data.
63 */
64typedef struct DRVNAT
65{
66 /** The network interface. */
67 PDMINETWORKCONNECTOR INetworkConnector;
68 /** The port we're attached to. */
69 PPDMINETWORKPORT pPort;
70 /** The network config of the port we're attached to. */
71 PPDMINETWORKCONFIG pConfig;
72 /** Pointer to the driver instance. */
73 PPDMDRVINS pDrvIns;
74 /** Link state */
75 PDMNETWORKLINKSTATE enmLinkState;
76 /** NAT state for this instance. */
77 PNATState pNATState;
78 /** TFTP directory prefix. */
79 char *pszTFTPPrefix;
80 /** Boot file name to provide in the DHCP server response. */
81 char *pszBootFile;
82 /** tftp server name to provide in the DHCP server response. */
83 char *pszNextServer;
84 /* polling thread */
85 PPDMTHREAD pThread;
86 /** Queue for NAT-thread-external events. */
87 PRTREQQUEUE pReqQueue;
88 /* Send queue */
89 PPDMQUEUE pSendQueue;
90#ifdef VBOX_WITH_SLIRP_MT
91 PPDMTHREAD pGuestThread;
92#endif
93#ifndef RT_OS_WINDOWS
94 /** The write end of the control pipe. */
95 RTFILE PipeWrite;
96 /** The read end of the control pipe. */
97 RTFILE PipeRead;
98#else
99 /** for external notification */
100 HANDLE hWakeupEvent;
101#endif
102} DRVNAT, *PDRVNAT;
103
104typedef struct DRVNATQUEUITEM
105{
106 /** The core part owned by the queue manager. */
107 PDMQUEUEITEMCORE Core;
108 /** The buffer for output to guest. */
109 const uint8_t *pu8Buf;
110 /* size of buffer */
111 size_t cb;
112 void *mbuf;
113} DRVNATQUEUITEM, *PDRVNATQUEUITEM;
114
115/** Converts a pointer to NAT::INetworkConnector to a PRDVNAT. */
116#define PDMINETWORKCONNECTOR_2_DRVNAT(pInterface) ( (PDRVNAT)((uintptr_t)pInterface - RT_OFFSETOF(DRVNAT, INetworkConnector)) )
117
118
119/**
120 * Worker function for drvNATSend().
121 * @thread "NAT" thread.
122 */
123static void drvNATSendWorker(PDRVNAT pThis, const void *pvBuf, size_t cb)
124{
125 Assert(pThis->enmLinkState == PDMNETWORKLINKSTATE_UP);
126 if (pThis->enmLinkState == PDMNETWORKLINKSTATE_UP)
127 slirp_input(pThis->pNATState, (uint8_t *)pvBuf, cb);
128}
129
130/**
131 * Send data to the network.
132 *
133 * @returns VBox status code.
134 * @param pInterface Pointer to the interface structure containing the called function pointer.
135 * @param pvBuf Data to send.
136 * @param cb Number of bytes to send.
137 * @thread EMT
138 */
139static DECLCALLBACK(int) drvNATSend(PPDMINETWORKCONNECTOR pInterface, const void *pvBuf, size_t cb)
140{
141 PDRVNAT pThis = PDMINETWORKCONNECTOR_2_DRVNAT(pInterface);
142
143 LogFlow(("drvNATSend: pvBuf=%p cb=%#x\n", pvBuf, cb));
144 Log2(("drvNATSend: pvBuf=%p cb=%#x\n%.*Rhxd\n", pvBuf, cb, cb, pvBuf));
145
146 PRTREQ pReq = NULL;
147 int rc;
148 void *buf;
149 /* don't queue new requests when the NAT thread is about to stop */
150 if (pThis->pThread->enmState != PDMTHREADSTATE_RUNNING)
151 return VINF_SUCCESS;
152#ifndef VBOX_WITH_SLIRP_MT
153 rc = RTReqAlloc(pThis->pReqQueue, &pReq, RTREQTYPE_INTERNAL);
154#else
155 rc = RTReqAlloc((PRTREQQUEUE)slirp_get_queue(pThis->pNATState), &pReq, RTREQTYPE_INTERNAL);
156#endif
157 AssertReleaseRC(rc);
158
159 /* @todo: Here we should get mbuf instead temporal buffer */
160 buf = RTMemAlloc(cb);
161 if (buf == NULL)
162 {
163 LogRel(("NAT: Can't allocate send buffer\n"));
164 return VERR_NO_MEMORY;
165 }
166 memcpy(buf, pvBuf, cb);
167
168 pReq->u.Internal.pfn = (PFNRT)drvNATSendWorker;
169 pReq->u.Internal.cArgs = 3;
170 pReq->u.Internal.aArgs[0] = (uintptr_t)pThis;
171 pReq->u.Internal.aArgs[1] = (uintptr_t)buf;
172 pReq->u.Internal.aArgs[2] = (uintptr_t)cb;
173 pReq->fFlags = RTREQFLAGS_VOID|RTREQFLAGS_NO_WAIT;
174
175 rc = RTReqQueue(pReq, 0); /* don't wait, we have to wakeup the NAT thread fist */
176 AssertReleaseRC(rc);
177#ifndef RT_OS_WINDOWS
178 /* kick select() */
179 rc = RTFileWrite(pThis->PipeWrite, "", 1, NULL);
180 AssertRC(rc);
181#else
182 /* kick WSAWaitForMultipleEvents */
183 rc = WSASetEvent(pThis->hWakeupEvent);
184 AssertRelease(rc == TRUE);
185#endif
186
187 LogFlow(("drvNATSend: end\n"));
188 return VINF_SUCCESS;
189}
190
191
192/**
193 * Set promiscuous mode.
194 *
195 * This is called when the promiscuous mode is set. This means that there doesn't have
196 * to be a mode change when it's called.
197 *
198 * @param pInterface Pointer to the interface structure containing the called function pointer.
199 * @param fPromiscuous Set if the adaptor is now in promiscuous mode. Clear if it is not.
200 * @thread EMT
201 */
202static DECLCALLBACK(void) drvNATSetPromiscuousMode(PPDMINETWORKCONNECTOR pInterface, bool fPromiscuous)
203{
204 LogFlow(("drvNATSetPromiscuousMode: fPromiscuous=%d\n", fPromiscuous));
205 /* nothing to do */
206}
207
208/**
209 * Worker function for drvNATNotifyLinkChanged().
210 * @thread "NAT" thread.
211 */
212static void drvNATNotifyLinkChangedWorker(PDRVNAT pThis, PDMNETWORKLINKSTATE enmLinkState)
213{
214 pThis->enmLinkState = enmLinkState;
215
216 switch (enmLinkState)
217 {
218 case PDMNETWORKLINKSTATE_UP:
219 LogRel(("NAT: link up\n"));
220 slirp_link_up(pThis->pNATState);
221 break;
222
223 case PDMNETWORKLINKSTATE_DOWN:
224 case PDMNETWORKLINKSTATE_DOWN_RESUME:
225 LogRel(("NAT: link down\n"));
226 slirp_link_down(pThis->pNATState);
227 break;
228
229 default:
230 AssertMsgFailed(("drvNATNotifyLinkChanged: unexpected link state %d\n", enmLinkState));
231 }
232}
233
234/**
235 * Notification on link status changes.
236 *
237 * @param pInterface Pointer to the interface structure containing the called function pointer.
238 * @param enmLinkState The new link state.
239 * @thread EMT
240 */
241static DECLCALLBACK(void) drvNATNotifyLinkChanged(PPDMINETWORKCONNECTOR pInterface, PDMNETWORKLINKSTATE enmLinkState)
242{
243 PDRVNAT pThis = PDMINETWORKCONNECTOR_2_DRVNAT(pInterface);
244
245 LogFlow(("drvNATNotifyLinkChanged: enmLinkState=%d\n", enmLinkState));
246
247 PRTREQ pReq = NULL;
248 /* don't queue new requests when the NAT thread is about to stop */
249 if (pThis->pThread->enmState != PDMTHREADSTATE_RUNNING)
250 return;
251 int rc = RTReqAlloc(pThis->pReqQueue, &pReq, RTREQTYPE_INTERNAL);
252 AssertReleaseRC(rc);
253 pReq->u.Internal.pfn = (PFNRT)drvNATNotifyLinkChangedWorker;
254 pReq->u.Internal.cArgs = 2;
255 pReq->u.Internal.aArgs[0] = (uintptr_t)pThis;
256 pReq->u.Internal.aArgs[1] = (uintptr_t)enmLinkState;
257 pReq->fFlags = RTREQFLAGS_VOID;
258 rc = RTReqQueue(pReq, 0); /* don't wait, we have to wakeup the NAT thread fist */
259 if (RT_LIKELY(rc == VERR_TIMEOUT))
260 {
261#ifndef RT_OS_WINDOWS
262 /* kick select() */
263 rc = RTFileWrite(pThis->PipeWrite, "", 1, NULL);
264 AssertRC(rc);
265#else
266 /* kick WSAWaitForMultipleEvents() */
267 rc = WSASetEvent(pThis->hWakeupEvent);
268 AssertRelease(rc == TRUE);
269#endif
270 rc = RTReqWait(pReq, RT_INDEFINITE_WAIT);
271 AssertReleaseRC(rc);
272 }
273 else
274 AssertReleaseRC(rc);
275 RTReqFree(pReq);
276}
277
278
279static DECLCALLBACK(int) drvNATAsyncIoThread(PPDMDRVINS pDrvIns, PPDMTHREAD pThread)
280{
281 PDRVNAT pThis = PDMINS_2_DATA(pDrvIns, PDRVNAT);
282 int nFDs = -1;
283 unsigned int ms;
284#ifdef RT_OS_WINDOWS
285 DWORD event;
286 HANDLE *phEvents;
287 unsigned int cBreak = 0;
288#else /* RT_OS_WINDOWS */
289 struct pollfd *polls = NULL;
290 unsigned int cPollNegRet = 0;
291#endif /* !RT_OS_WINDOWS */
292
293 LogFlow(("drvNATAsyncIoThread: pThis=%p\n", pThis));
294
295 if (pThread->enmState == PDMTHREADSTATE_INITIALIZING)
296 return VINF_SUCCESS;
297
298#ifdef RT_OS_WINDOWS
299 phEvents = slirp_get_events(pThis->pNATState);
300#endif /* RT_OS_WINDOWS */
301
302 /*
303 * Polling loop.
304 */
305 while (pThread->enmState == PDMTHREADSTATE_RUNNING)
306 {
307 nFDs = -1;
308
309 /*
310 * To prevent concurent execution of sending/receving threads
311 */
312#ifndef RT_OS_WINDOWS
313 nFDs = slirp_get_nsock(pThis->pNATState);
314 polls = NULL;
315 /* allocation for all sockets + Management pipe */
316 polls = (struct pollfd *)RTMemAlloc((1 + nFDs) * sizeof(struct pollfd) + sizeof(uint32_t));
317 if (polls == NULL)
318 return VERR_NO_MEMORY;
319
320 /* don't pass the managemant pipe */
321 slirp_select_fill(pThis->pNATState, &nFDs, &polls[1]);
322 ms = slirp_get_timeout_ms(pThis->pNATState);
323
324 polls[0].fd = pThis->PipeRead;
325 /* POLLRDBAND usually doesn't used on Linux but seems used on Solaris */
326 polls[0].events = POLLRDNORM|POLLPRI|POLLRDBAND;
327 polls[0].revents = 0;
328
329 int cChangedFDs = poll(polls, nFDs + 1, ms ? ms : -1);
330 if (cChangedFDs < 0)
331 {
332 if (errno == EINTR)
333 {
334 Log2(("NAT: signal was caught while sleep on poll\n"));
335 /* No error, just process all outstanding requests but don't wait */
336 cChangedFDs = 0;
337 }
338 else if (cPollNegRet++ > 128)
339 {
340 LogRel(("NAT:Poll returns (%s) suppressed %d\n", strerror(errno), cPollNegRet));
341 cPollNegRet = 0;
342 }
343 }
344
345 if (cChangedFDs >= 0)
346 {
347 slirp_select_poll(pThis->pNATState, &polls[1], nFDs);
348 if (polls[0].revents & (POLLRDNORM|POLLPRI|POLLRDBAND))
349 {
350 /* drain the pipe */
351 char ch[1];
352 size_t cbRead;
353 int counter = 0;
354 /*
355 * drvNATSend decoupled so we don't know how many times
356 * device's thread sends before we've entered multiplex,
357 * so to avoid false alarm drain pipe here to the very end
358 *
359 * @todo: Probably we should counter drvNATSend to count how
360 * deep pipe has been filed before drain.
361 *
362 * XXX:Make it reading exactly we need to drain the pipe.
363 */
364 RTFileRead(pThis->PipeRead, &ch, 1, &cbRead);
365 }
366 }
367 /* process _all_ outstanding requests but don't wait */
368 RTReqProcess(pThis->pReqQueue, 0);
369 RTMemFree(polls);
370#else /* RT_OS_WINDOWS */
371 slirp_select_fill(pThis->pNATState, &nFDs);
372 ms = slirp_get_timeout_ms(pThis->pNATState);
373 struct timeval tv = { 0, ms*1000 };
374 event = WSAWaitForMultipleEvents(nFDs, phEvents, FALSE, ms ? ms : WSA_INFINITE, FALSE);
375 if ( (event < WSA_WAIT_EVENT_0 || event > WSA_WAIT_EVENT_0 + nFDs - 1)
376 && event != WSA_WAIT_TIMEOUT)
377 {
378 int error = WSAGetLastError();
379 LogRel(("NAT: WSAWaitForMultipleEvents returned %d (error %d)\n", event, error));
380 RTAssertReleasePanic();
381 }
382
383 if (event == WSA_WAIT_TIMEOUT)
384 {
385 /* only check for slow/fast timers */
386 slirp_select_poll(pThis->pNATState, /* fTimeout=*/true, /*fIcmp=*/false);
387 Log2(("%s: timeout\n", __FUNCTION__));
388 continue;
389 }
390
391 /* poll the sockets in any case */
392 Log2(("%s: poll\n", __FUNCTION__));
393 slirp_select_poll(pThis->pNATState, /* fTimeout=*/false, /* fIcmp=*/(event == WSA_WAIT_EVENT_0));
394 /* process _all_ outstanding requests but don't wait */
395 RTReqProcess(pThis->pReqQueue, 0);
396# ifdef VBOX_NAT_DELAY_HACK
397 if (cBreak++ > 128)
398 {
399 cBreak = 0;
400 RTThreadSleep(2);
401 }
402# endif
403#endif /* RT_OS_WINDOWS */
404 }
405
406 return VINF_SUCCESS;
407}
408
409 /**
410 * Unblock the send thread so it can respond to a state change.
411 *
412 * @returns VBox status code.
413 * @param pDevIns The pcnet device instance.
414 * @param pThread The send thread.
415 */
416static DECLCALLBACK(int) drvNATAsyncIoWakeup(PPDMDRVINS pDrvIns, PPDMTHREAD pThread)
417{
418 PDRVNAT pThis = PDMINS_2_DATA(pDrvIns, PDRVNAT);
419
420#ifndef RT_OS_WINDOWS
421 /* kick select() */
422 int rc = RTFileWrite(pThis->PipeWrite, "", 1, NULL);
423 AssertRC(rc);
424#else /* !RT_OS_WINDOWS */
425 /* kick WSAWaitForMultipleEvents() */
426 WSASetEvent(pThis->hWakeupEvent);
427#endif /* RT_OS_WINDOWS */
428
429 return VINF_SUCCESS;
430}
431
432#ifdef VBOX_WITH_SLIRP_MT
433static DECLCALLBACK(int) drvNATAsyncIoGuest(PPDMDRVINS pDrvIns, PPDMTHREAD pThread)
434{
435 PDRVNAT pThis = PDMINS_2_DATA(pDrvIns, PDRVNAT);
436 if (pThread->enmState == PDMTHREADSTATE_INITIALIZING)
437 return VINF_SUCCESS;
438 while (pThread->enmState == PDMTHREADSTATE_RUNNING)
439 {
440 slirp_process_queue(pThis->pNATState);
441 }
442 return VINF_SUCCESS;
443}
444
445static DECLCALLBACK(int) drvNATAsyncIoGuestWakeup(PPDMDRVINS pDrvIns, PPDMTHREAD pThread)
446{
447 PDRVNAT pThis = PDMINS_2_DATA(pDrvIns, PDRVNAT);
448
449 return VINF_SUCCESS;
450}
451#endif /* VBOX_WITH_SLIRP_MT */
452
453
454/**
455 * Function called by slirp to check if it's possible to feed incoming data to the network port.
456 * @returns 1 if possible.
457 * @returns 0 if not possible.
458 */
459int slirp_can_output(void *pvUser)
460{
461 PDRVNAT pThis = (PDRVNAT)pvUser;
462
463 Assert(pThis);
464 return 1;
465}
466
467
468/**
469 * Function called by slirp to feed incoming data to the network port.
470 */
471void slirp_output(void *pvUser, void *pvArg, const uint8_t *pu8Buf, int cb)
472{
473 PDRVNAT pThis = (PDRVNAT)pvUser;
474
475 LogFlow(("slirp_output BEGIN %x %d\n", pu8Buf, cb));
476 Log2(("slirp_output: pu8Buf=%p cb=%#x (pThis=%p)\n%.*Rhxd\n", pu8Buf, cb, pThis, cb, pu8Buf));
477
478 Assert(pThis);
479
480 PDRVNATQUEUITEM pItem = (PDRVNATQUEUITEM)PDMQueueAlloc(pThis->pSendQueue);
481 if (pItem)
482 {
483 pItem->pu8Buf = pu8Buf;
484 pItem->cb = cb;
485 pItem->mbuf = pvArg;
486 Log2(("pItem:%p %.Rhxd\n", pItem, pItem->pu8Buf));
487 PDMQueueInsert(pThis->pSendQueue, &pItem->Core);
488 return;
489 }
490 static unsigned cDroppedPackets;
491 if (cDroppedPackets < 64)
492 {
493 cDroppedPackets++;
494 }
495 else
496 {
497 LogRel(("NAT: %d messages suppressed about dropping package (couldn't allocate queue item)\n", cDroppedPackets));
498 cDroppedPackets = 0;
499 }
500 RTMemFree((void *)pu8Buf);
501}
502
503/**
504 * Queue callback for processing a queued item.
505 *
506 * @returns Success indicator.
507 * If false the item will not be removed and the flushing will stop.
508 * @param pDrvIns The driver instance.
509 * @param pItemCore Pointer to the queue item to process.
510 */
511static DECLCALLBACK(bool) drvNATQueueConsumer(PPDMDRVINS pDrvIns, PPDMQUEUEITEMCORE pItemCore)
512{
513 PDRVNAT pThis = PDMINS_2_DATA(pDrvIns, PDRVNAT);
514 PDRVNATQUEUITEM pItem = (PDRVNATQUEUITEM)pItemCore;
515 PRTREQ pReq = NULL;
516 Log(("drvNATQueueConsumer(pItem:%p, pu8Buf:%p, cb:%d)\n", pItem, pItem->pu8Buf, pItem->cb));
517 Log2(("drvNATQueueConsumer: pu8Buf:\n%.Rhxd\n", pItem->pu8Buf));
518 int rc = pThis->pPort->pfnWaitReceiveAvail(pThis->pPort, 0);
519 if (RT_FAILURE(rc))
520 return false;
521 rc = pThis->pPort->pfnReceive(pThis->pPort, pItem->pu8Buf, pItem->cb);
522
523#if 0
524 rc = RTReqAlloc(pThis->pReqQueue, &pReq, RTREQTYPE_INTERNAL);
525 AssertReleaseRC(rc);
526 pReq->u.Internal.pfn = (PFNRT)slirp_post_sent;
527 pReq->u.Internal.cArgs = 2;
528 pReq->u.Internal.aArgs[0] = (uintptr_t)pThis->pNATState;
529 pReq->u.Internal.aArgs[1] = (uintptr_t)pItem->mbuf;
530 pReq->fFlags = RTREQFLAGS_VOID;
531 AssertRC(rc);
532#else
533 /*Copy buffer again, till seeking good way of syncronization with slirp mbuf management code*/
534 AssertRelease(pItem->mbuf == NULL);
535 RTMemFree((void *)pItem->pu8Buf);
536#endif
537 return RT_SUCCESS(rc);
538}
539
540/**
541 * Queries an interface to the driver.
542 *
543 * @returns Pointer to interface.
544 * @returns NULL if the interface was not supported by the driver.
545 * @param pInterface Pointer to this interface structure.
546 * @param enmInterface The requested interface identification.
547 * @thread Any thread.
548 */
549static DECLCALLBACK(void *) drvNATQueryInterface(PPDMIBASE pInterface, PDMINTERFACE enmInterface)
550{
551 PPDMDRVINS pDrvIns = PDMIBASE_2_PDMDRV(pInterface);
552 PDRVNAT pThis = PDMINS_2_DATA(pDrvIns, PDRVNAT);
553 switch (enmInterface)
554 {
555 case PDMINTERFACE_BASE:
556 return &pDrvIns->IBase;
557 case PDMINTERFACE_NETWORK_CONNECTOR:
558 return &pThis->INetworkConnector;
559 default:
560 return NULL;
561 }
562}
563
564
565/**
566 * Destruct a driver instance.
567 *
568 * Most VM resources are freed by the VM. This callback is provided so that any non-VM
569 * resources can be freed correctly.
570 *
571 * @param pDrvIns The driver instance data.
572 */
573static DECLCALLBACK(void) drvNATDestruct(PPDMDRVINS pDrvIns)
574{
575 PDRVNAT pThis = PDMINS_2_DATA(pDrvIns, PDRVNAT);
576
577 LogFlow(("drvNATDestruct:\n"));
578
579 slirp_term(pThis->pNATState);
580 pThis->pNATState = NULL;
581}
582
583
584/**
585 * Sets up the redirectors.
586 *
587 * @returns VBox status code.
588 * @param pCfgHandle The drivers configuration handle.
589 */
590static int drvNATConstructRedir(unsigned iInstance, PDRVNAT pThis, PCFGMNODE pCfgHandle, RTIPV4ADDR Network)
591{
592 /*
593 * Enumerate redirections.
594 */
595 for (PCFGMNODE pNode = CFGMR3GetFirstChild(pCfgHandle); pNode; pNode = CFGMR3GetNextChild(pNode))
596 {
597 /*
598 * Validate the port forwarding config.
599 */
600 if (!CFGMR3AreValuesValid(pNode, "Protocol\0UDP\0HostPort\0GuestPort\0GuestIP\0"))
601 return PDMDRV_SET_ERROR(pThis->pDrvIns, VERR_PDM_DRVINS_UNKNOWN_CFG_VALUES, N_("Unknown configuration in port forwarding"));
602
603 /* protocol type */
604 bool fUDP;
605 char szProtocol[32];
606 int rc = CFGMR3QueryString(pNode, "Protocol", &szProtocol[0], sizeof(szProtocol));
607 if (rc == VERR_CFGM_VALUE_NOT_FOUND)
608 {
609 rc = CFGMR3QueryBool(pNode, "UDP", &fUDP);
610 if (rc == VERR_CFGM_VALUE_NOT_FOUND)
611 fUDP = false;
612 else if (RT_FAILURE(rc))
613 return PDMDrvHlpVMSetError(pThis->pDrvIns, rc, RT_SRC_POS, N_("NAT#%d: configuration query for \"UDP\" boolean failed"), iInstance);
614 }
615 else if (RT_SUCCESS(rc))
616 {
617 if (!RTStrICmp(szProtocol, "TCP"))
618 fUDP = false;
619 else if (!RTStrICmp(szProtocol, "UDP"))
620 fUDP = true;
621 else
622 return PDMDrvHlpVMSetError(pThis->pDrvIns, VERR_INVALID_PARAMETER, RT_SRC_POS, N_("NAT#%d: Invalid configuration value for \"Protocol\": \"%s\""), iInstance, szProtocol);
623 }
624 else
625 return PDMDrvHlpVMSetError(pThis->pDrvIns, rc, RT_SRC_POS, N_("NAT#%d: configuration query for \"Protocol\" string failed"), iInstance);
626
627 /* host port */
628 int32_t iHostPort;
629 rc = CFGMR3QueryS32(pNode, "HostPort", &iHostPort);
630 if (RT_FAILURE(rc))
631 return PDMDrvHlpVMSetError(pThis->pDrvIns, rc, RT_SRC_POS, N_("NAT#%d: configuration query for \"HostPort\" integer failed"), iInstance);
632
633 /* guest port */
634 int32_t iGuestPort;
635 rc = CFGMR3QueryS32(pNode, "GuestPort", &iGuestPort);
636 if (RT_FAILURE(rc))
637 return PDMDrvHlpVMSetError(pThis->pDrvIns, rc, RT_SRC_POS, N_("NAT#%d: configuration query for \"GuestPort\" integer failed"), iInstance);
638
639 /* guest address */
640 char szGuestIP[32];
641 rc = CFGMR3QueryString(pNode, "GuestIP", &szGuestIP[0], sizeof(szGuestIP));
642 if (rc == VERR_CFGM_VALUE_NOT_FOUND)
643 RTStrPrintf(szGuestIP, sizeof(szGuestIP), "%d.%d.%d.%d",
644 (Network & 0xFF000000) >> 24, (Network & 0xFF0000) >> 16, (Network & 0xFF00) >> 8, (Network & 0xE0) | 15);
645 else if (RT_FAILURE(rc))
646 return PDMDrvHlpVMSetError(pThis->pDrvIns, rc, RT_SRC_POS, N_("NAT#%d: configuration query for \"GuestIP\" string failed"), iInstance);
647 struct in_addr GuestIP;
648 if (!inet_aton(szGuestIP, &GuestIP))
649 return PDMDrvHlpVMSetError(pThis->pDrvIns, VERR_NAT_REDIR_GUEST_IP, RT_SRC_POS,
650 N_("NAT#%d: configuration error: invalid \"GuestIP\"=\"%s\", inet_aton failed"), iInstance, szGuestIP);
651
652 /*
653 * Call slirp about it.
654 */
655 Log(("drvNATConstruct: Redir %d -> %s:%d\n", iHostPort, szGuestIP, iGuestPort));
656 if (slirp_redir(pThis->pNATState, fUDP, iHostPort, GuestIP, iGuestPort) < 0)
657 return PDMDrvHlpVMSetError(pThis->pDrvIns, VERR_NAT_REDIR_SETUP, RT_SRC_POS,
658 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);
659 } /* for each redir rule */
660
661 return VINF_SUCCESS;
662}
663
664/**
665 * Get the MAC address into the slirp stack.
666 */
667static void drvNATSetMac(PDRVNAT pThis)
668{
669 if (pThis->pConfig)
670 {
671 RTMAC Mac;
672 pThis->pConfig->pfnGetMac(pThis->pConfig, &Mac);
673 slirp_set_ethaddr(pThis->pNATState, Mac.au8);
674 }
675}
676
677
678/**
679 * After loading we have to pass the MAC address of the ethernet device to the slirp stack.
680 * Otherwise the guest is not reachable until it performs a DHCP request or an ARP request
681 * (usually done during guest boot).
682 */
683static DECLCALLBACK(int) drvNATLoadDone(PPDMDRVINS pDrvIns, PSSMHANDLE pSSMHandle)
684{
685 PDRVNAT pThis = PDMINS_2_DATA(pDrvIns, PDRVNAT);
686 drvNATSetMac(pThis);
687 return VINF_SUCCESS;
688}
689
690
691/**
692 * Some guests might not use DHCP to retrieve an IP but use a static IP.
693 */
694static DECLCALLBACK(void) drvNATPowerOn(PPDMDRVINS pDrvIns)
695{
696 PDRVNAT pThis = PDMINS_2_DATA(pDrvIns, PDRVNAT);
697 drvNATSetMac(pThis);
698}
699
700
701/**
702 * Construct a NAT network transport driver instance.
703 *
704 * @returns VBox status.
705 * @param pDrvIns The driver instance data.
706 * If the registration structure is needed, pDrvIns->pDrvReg points to it.
707 * @param pCfgHandle Configuration node handle for the driver. Use this to obtain the configuration
708 * of the driver instance. It's also found in pDrvIns->pCfgHandle, but like
709 * iInstance it's expected to be used a bit in this function.
710 */
711static DECLCALLBACK(int) drvNATConstruct(PPDMDRVINS pDrvIns, PCFGMNODE pCfgHandle)
712{
713 PDRVNAT pThis = PDMINS_2_DATA(pDrvIns, PDRVNAT);
714 char szNetAddr[16];
715 char szNetwork[32]; /* xxx.xxx.xxx.xxx/yy */
716 LogFlow(("drvNATConstruct:\n"));
717
718 /*
719 * Validate the config.
720 */
721#ifndef VBOX_WITH_SLIRP_DNS_PROXY
722 if (!CFGMR3AreValuesValid(pCfgHandle, "PassDomain\0TFTPPrefix\0BootFile\0Network\0NextServer\0"))
723#else
724 if (!CFGMR3AreValuesValid(pCfgHandle, "PassDomain\0TFTPPrefix\0BootFile\0Network\0NextServer\0DNSProxy\0"))
725#endif
726 return PDMDRV_SET_ERROR(pDrvIns, VERR_PDM_DRVINS_UNKNOWN_CFG_VALUES, N_("Unknown NAT configuration option, only supports PassDomain, TFTPPrefix, BootFile and Network"));
727
728 /*
729 * Init the static parts.
730 */
731 pThis->pDrvIns = pDrvIns;
732 pThis->pNATState = NULL;
733 pThis->pszTFTPPrefix = NULL;
734 pThis->pszBootFile = NULL;
735 pThis->pszNextServer = NULL;
736 /* IBase */
737 pDrvIns->IBase.pfnQueryInterface = drvNATQueryInterface;
738 /* INetwork */
739 pThis->INetworkConnector.pfnSend = drvNATSend;
740 pThis->INetworkConnector.pfnSetPromiscuousMode = drvNATSetPromiscuousMode;
741 pThis->INetworkConnector.pfnNotifyLinkChanged = drvNATNotifyLinkChanged;
742
743 /*
744 * Get the configuration settings.
745 */
746 bool fPassDomain = true;
747 int rc = CFGMR3QueryBool(pCfgHandle, "PassDomain", &fPassDomain);
748 if (rc == VERR_CFGM_VALUE_NOT_FOUND)
749 fPassDomain = true;
750 else if (RT_FAILURE(rc))
751 return PDMDrvHlpVMSetError(pDrvIns, rc, RT_SRC_POS, N_("NAT#%d: configuration query for \"PassDomain\" boolean failed"), pDrvIns->iInstance);
752
753 rc = CFGMR3QueryStringAlloc(pCfgHandle, "TFTPPrefix", &pThis->pszTFTPPrefix);
754 if (RT_FAILURE(rc) && rc != VERR_CFGM_VALUE_NOT_FOUND)
755 return PDMDrvHlpVMSetError(pDrvIns, rc, RT_SRC_POS, N_("NAT#%d: configuration query for \"TFTPPrefix\" string failed"), pDrvIns->iInstance);
756 rc = CFGMR3QueryStringAlloc(pCfgHandle, "BootFile", &pThis->pszBootFile);
757 if (RT_FAILURE(rc) && rc != VERR_CFGM_VALUE_NOT_FOUND)
758 return PDMDrvHlpVMSetError(pDrvIns, rc, RT_SRC_POS, N_("NAT#%d: configuration query for \"BootFile\" string failed"), pDrvIns->iInstance);
759 rc = CFGMR3QueryStringAlloc(pCfgHandle, "NextServer", &pThis->pszNextServer);
760 if (RT_FAILURE(rc) && rc != VERR_CFGM_VALUE_NOT_FOUND)
761 return PDMDrvHlpVMSetError(pDrvIns, rc, RT_SRC_POS, N_("NAT#%d: configuration query for \"NextServer\" string failed"), pDrvIns->iInstance);
762#ifdef VBOX_WITH_SLIRP_DNS_PROXY
763 int fDNSProxy;
764 rc = CFGMR3QueryS32(pCfgHandle, "DNSProxy", &fDNSProxy);
765 if (rc == VERR_CFGM_VALUE_NOT_FOUND)
766 fDNSProxy = 0;
767#endif
768
769 /*
770 * Query the network port interface.
771 */
772 pThis->pPort = (PPDMINETWORKPORT)pDrvIns->pUpBase->pfnQueryInterface(pDrvIns->pUpBase, PDMINTERFACE_NETWORK_PORT);
773 if (!pThis->pPort)
774 return PDMDRV_SET_ERROR(pDrvIns, VERR_PDM_MISSING_INTERFACE_ABOVE,
775 N_("Configuration error: the above device/driver didn't export the network port interface"));
776 pThis->pConfig = (PPDMINETWORKCONFIG)pDrvIns->pUpBase->pfnQueryInterface(pDrvIns->pUpBase, PDMINTERFACE_NETWORK_CONFIG);
777 if (!pThis->pConfig)
778 return PDMDRV_SET_ERROR(pDrvIns, VERR_PDM_MISSING_INTERFACE_ABOVE,
779 N_("Configuration error: the above device/driver didn't export the network config interface"));
780
781 /* Generate a network address for this network card. */
782 rc = CFGMR3QueryString(pCfgHandle, "Network", szNetwork, sizeof(szNetwork));
783 if (rc == VERR_CFGM_VALUE_NOT_FOUND)
784 RTStrPrintf(szNetwork, sizeof(szNetwork), "10.0.%d.0/24", pDrvIns->iInstance + 2);
785 else if (RT_FAILURE(rc))
786 return PDMDrvHlpVMSetError(pDrvIns, rc, RT_SRC_POS, N_("NAT#%d: configuration query for \"Network\" string failed"), pDrvIns->iInstance);
787
788 RTIPV4ADDR Network;
789 RTIPV4ADDR Netmask;
790 rc = RTCidrStrToIPv4(szNetwork, &Network, &Netmask);
791 if (RT_FAILURE(rc))
792 return PDMDrvHlpVMSetError(pDrvIns, rc, RT_SRC_POS, N_("NAT#%d: Configuration error: network '%s' describes not a valid IPv4 network"), pDrvIns->iInstance, szNetwork);
793
794 RTStrPrintf(szNetAddr, sizeof(szNetAddr), "%d.%d.%d.%d",
795 (Network & 0xFF000000) >> 24, (Network & 0xFF0000) >> 16, (Network & 0xFF00) >> 8, Network & 0xFF);
796
797 /*
798 * Initialize slirp.
799 */
800 rc = slirp_init(&pThis->pNATState, &szNetAddr[0], Netmask, fPassDomain, pThis);
801 if (RT_SUCCESS(rc))
802 {
803 slirp_set_dhcp_TFTP_prefix(pThis->pNATState, pThis->pszTFTPPrefix);
804 slirp_set_dhcp_TFTP_bootfile(pThis->pNATState, pThis->pszBootFile);
805 slirp_set_dhcp_next_server(pThis->pNATState, pThis->pszNextServer);
806#ifdef VBOX_WITH_SLIRP_DNS_PROXY
807 slirp_set_dhcp_dns_proxy(pThis->pNATState, fDNSProxy);
808#endif
809
810 slirp_register_timers(pThis->pNATState, pDrvIns);
811 int rc2 = drvNATConstructRedir(pDrvIns->iInstance, pThis, pCfgHandle, Network);
812 if (RT_SUCCESS(rc2))
813 {
814 /*
815 * Register a load done notification to get the MAC address into the slirp
816 * engine after we loaded a guest state.
817 */
818 rc2 = PDMDrvHlpSSMRegister(pDrvIns, pDrvIns->pDrvReg->szDriverName,
819 pDrvIns->iInstance, 0, 0,
820 NULL, NULL, NULL, NULL, NULL, drvNATLoadDone);
821 AssertRC(rc2);
822 rc = RTReqCreateQueue(&pThis->pReqQueue);
823 if (RT_FAILURE(rc))
824 {
825 LogRel(("NAT: Can't create request queue\n"));
826 return rc;
827 }
828
829 rc = PDMDrvHlpPDMQueueCreate(pDrvIns, sizeof(DRVNATQUEUITEM), 50, 0, drvNATQueueConsumer, &pThis->pSendQueue);
830 if (RT_FAILURE(rc))
831 {
832 LogRel(("NAT: Can't create send queue\n"));
833 return rc;
834 }
835
836#ifndef RT_OS_WINDOWS
837 /*
838 * Create the control pipe.
839 */
840 int fds[2];
841 if (pipe(&fds[0]) != 0) /** @todo RTPipeCreate() or something... */
842 {
843 int rc = RTErrConvertFromErrno(errno);
844 AssertRC(rc);
845 return rc;
846 }
847 pThis->PipeRead = fds[0];
848 pThis->PipeWrite = fds[1];
849#else
850 pThis->hWakeupEvent = CreateEvent(NULL, FALSE, FALSE, NULL); /* auto-reset event */
851 slirp_register_external_event(pThis->pNATState, pThis->hWakeupEvent, VBOX_WAKEUP_EVENT_INDEX);
852#endif
853
854 rc = PDMDrvHlpPDMThreadCreate(pDrvIns, &pThis->pThread, pThis, drvNATAsyncIoThread, drvNATAsyncIoWakeup, 128 * _1K, RTTHREADTYPE_IO, "NAT");
855 AssertReleaseRC(rc);
856
857#ifdef VBOX_WITH_SLIRP_MT
858 rc = PDMDrvHlpPDMThreadCreate(pDrvIns, &pThis->pGuestThread, pThis, drvNATAsyncIoGuest, drvNATAsyncIoGuestWakeup, 128 * _1K, RTTHREADTYPE_IO, "NATGUEST");
859 AssertReleaseRC(rc);
860#endif
861
862 pThis->enmLinkState = PDMNETWORKLINKSTATE_UP;
863
864 /* might return VINF_NAT_DNS */
865 return rc;
866 }
867 /* failure path */
868 rc = rc2;
869 slirp_term(pThis->pNATState);
870 pThis->pNATState = NULL;
871 }
872 else
873 {
874 PDMDRV_SET_ERROR(pDrvIns, rc, N_("Unknown error during NAT networking setup: "));
875 AssertMsgFailed(("Add error message for rc=%d (%Rrc)\n", rc, rc));
876 }
877
878 return rc;
879}
880
881
882/**
883 * NAT network transport driver registration record.
884 */
885const PDMDRVREG g_DrvNAT =
886{
887 /* u32Version */
888 PDM_DRVREG_VERSION,
889 /* szDriverName */
890 "NAT",
891 /* pszDescription */
892 "NAT Network Transport Driver",
893 /* fFlags */
894 PDM_DRVREG_FLAGS_HOST_BITS_DEFAULT,
895 /* fClass. */
896 PDM_DRVREG_CLASS_NETWORK,
897 /* cMaxInstances */
898 16,
899 /* cbInstance */
900 sizeof(DRVNAT),
901 /* pfnConstruct */
902 drvNATConstruct,
903 /* pfnDestruct */
904 drvNATDestruct,
905 /* pfnIOCtl */
906 NULL,
907 /* pfnPowerOn */
908 drvNATPowerOn,
909 /* pfnReset */
910 NULL,
911 /* pfnSuspend */
912 NULL,
913 /* pfnResume */
914 NULL,
915 /* pfnDetach */
916 NULL,
917 /* pfnPowerOff */
918 NULL
919};
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