VirtualBox

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

Last change on this file since 19020 was 19014, checked in by vboxsync, 16 years ago

NAT: suppressed message

  • Property svn:eol-style set to native
  • Property svn:keywords set to Author Date Id Revision
File size: 31.5 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 polls = (struct pollfd *)RTMemAlloc((1 + nFDs) * sizeof(struct pollfd) + sizeof(uint32_t)); /* allocation for all sockets + Management pipe*/
316 if (polls == NULL)
317 return VERR_NO_MEMORY;
318
319 slirp_select_fill(pThis->pNATState, &nFDs, &polls[1]); /*don't bother Slirp with knowelege about managemant pipe*/
320 ms = slirp_get_timeout_ms(pThis->pNATState);
321
322 polls[0].fd = pThis->PipeRead;
323 polls[0].events = POLLRDNORM|POLLPRI|POLLRDBAND; /* POLLRDBAND usually doesn't used on Linux but seems used on Solaris */
324 polls[0].revents = 0;
325
326 int cChangedFDs = poll(polls, nFDs + 1, ms ? ms : -1);
327 /* 2.6.23 + gdb -> hitting all the time. probably a bug in poll/ptrace/whatever. */
328 if (cChangedFDs < 0)
329 {
330 if (cPollNegRet++ > 128)
331 {
332 LogRel(("Poll returns (%s) suppressed %d\n", strerror(errno), cPollNegRet));
333 cPollNegRet = 0;
334 }
335 }
336
337 if (cChangedFDs >= 0)
338 {
339 slirp_select_poll(pThis->pNATState, &polls[1], nFDs);
340 if (polls[0].revents & (POLLRDNORM|POLLPRI|POLLRDBAND))
341 {
342 /* drain the pipe */
343 char ch[1];
344 size_t cbRead;
345 int counter = 0;
346 /*
347 * drvNATSend decoupled so we don't know how many times
348 * device's thread sends before we've entered multiplex,
349 * so to avoid false alarm drain pipe here to the very end
350 *
351 * @todo: Probably we should counter drvNATSend to count how
352 * deep pipe has been filed before drain.
353 *
354 * XXX:Make it reading exactly we need to drain the pipe.
355 */
356 RTFileRead(pThis->PipeRead, &ch, 1, &cbRead);
357 }
358 /* process _all_ outstanding requests but don't wait */
359 RTReqProcess(pThis->pReqQueue, 0);
360 }
361 RTMemFree(polls);
362#else /* RT_OS_WINDOWS */
363 slirp_select_fill(pThis->pNATState, &nFDs);
364 ms = slirp_get_timeout_ms(pThis->pNATState);
365 struct timeval tv = { 0, ms*1000 };
366 event = WSAWaitForMultipleEvents(nFDs, phEvents, FALSE, ms ? ms : WSA_INFINITE, FALSE);
367 if ( (event < WSA_WAIT_EVENT_0 || event > WSA_WAIT_EVENT_0 + nFDs - 1)
368 && event != WSA_WAIT_TIMEOUT)
369 {
370 int error = WSAGetLastError();
371 LogRel(("NAT: WSAWaitForMultipleEvents returned %d (error %d)\n", event, error));
372 RTAssertReleasePanic();
373 }
374
375 if (event == WSA_WAIT_TIMEOUT)
376 {
377 /* only check for slow/fast timers */
378 slirp_select_poll(pThis->pNATState, /* fTimeout=*/true, /*fIcmp=*/false);
379 Log2(("%s: timeout\n", __FUNCTION__));
380 continue;
381 }
382
383 /* poll the sockets in any case */
384 Log2(("%s: poll\n", __FUNCTION__));
385 slirp_select_poll(pThis->pNATState, /* fTimeout=*/false, /* fIcmp=*/(event == WSA_WAIT_EVENT_0));
386 /* process _all_ outstanding requests but don't wait */
387 RTReqProcess(pThis->pReqQueue, 0);
388# ifdef VBOX_NAT_DELAY_HACK
389 if (cBreak++ > 128)
390 {
391 cBreak = 0;
392 RTThreadSleep(2);
393 }
394# endif
395#endif /* RT_OS_WINDOWS */
396 }
397
398 return VINF_SUCCESS;
399}
400
401 /**
402 * Unblock the send thread so it can respond to a state change.
403 *
404 * @returns VBox status code.
405 * @param pDevIns The pcnet device instance.
406 * @param pThread The send thread.
407 */
408static DECLCALLBACK(int) drvNATAsyncIoWakeup(PPDMDRVINS pDrvIns, PPDMTHREAD pThread)
409{
410 PDRVNAT pThis = PDMINS_2_DATA(pDrvIns, PDRVNAT);
411
412#ifndef RT_OS_WINDOWS
413 /* kick select() */
414 int rc = RTFileWrite(pThis->PipeWrite, "", 1, NULL);
415 AssertRC(rc);
416#else /* !RT_OS_WINDOWS */
417 /* kick WSAWaitForMultipleEvents() */
418 WSASetEvent(pThis->hWakeupEvent);
419#endif /* RT_OS_WINDOWS */
420
421 return VINF_SUCCESS;
422}
423
424#ifdef VBOX_WITH_SLIRP_MT
425static DECLCALLBACK(int) drvNATAsyncIoGuest(PPDMDRVINS pDrvIns, PPDMTHREAD pThread)
426{
427 PDRVNAT pThis = PDMINS_2_DATA(pDrvIns, PDRVNAT);
428 if (pThread->enmState == PDMTHREADSTATE_INITIALIZING)
429 return VINF_SUCCESS;
430 while (pThread->enmState == PDMTHREADSTATE_RUNNING)
431 {
432 slirp_process_queue(pThis->pNATState);
433 }
434 return VINF_SUCCESS;
435}
436
437static DECLCALLBACK(int) drvNATAsyncIoGuestWakeup(PPDMDRVINS pDrvIns, PPDMTHREAD pThread)
438{
439 PDRVNAT pThis = PDMINS_2_DATA(pDrvIns, PDRVNAT);
440
441 return VINF_SUCCESS;
442}
443#endif /* VBOX_WITH_SLIRP_MT */
444
445
446/**
447 * Function called by slirp to check if it's possible to feed incoming data to the network port.
448 * @returns 1 if possible.
449 * @returns 0 if not possible.
450 */
451int slirp_can_output(void *pvUser)
452{
453 PDRVNAT pThis = (PDRVNAT)pvUser;
454
455 Assert(pThis);
456 return 1;
457}
458
459
460/**
461 * Function called by slirp to feed incoming data to the network port.
462 */
463void slirp_output(void *pvUser, void *pvArg, const uint8_t *pu8Buf, int cb)
464{
465 PDRVNAT pThis = (PDRVNAT)pvUser;
466
467 LogFlow(("slirp_output BEGIN %x %d\n", pu8Buf, cb));
468 Log2(("slirp_output: pu8Buf=%p cb=%#x (pThis=%p)\n%.*Rhxd\n", pu8Buf, cb, pThis, cb, pu8Buf));
469
470 Assert(pThis);
471
472 PDRVNATQUEUITEM pItem = (PDRVNATQUEUITEM)PDMQueueAlloc(pThis->pSendQueue);
473 if (pItem)
474 {
475 pItem->pu8Buf = pu8Buf;
476 pItem->cb = cb;
477 pItem->mbuf = pvArg;
478 Log2(("pItem:%p %.Rhxd\n", pItem, pItem->pu8Buf));
479 PDMQueueInsert(pThis->pSendQueue, &pItem->Core);
480 return;
481 }
482 static unsigned cDroppedPackets;
483 if (cDroppedPackets < 64)
484 {
485 cDroppedPackets++;
486 }
487 else
488 {
489 LogRel(("NAT: %d messages suppressed about dropping package (couldn't allocate queue item)\n", cDroppedPackets));
490 cDroppedPackets = 0;
491 }
492 RTMemFree((void *)pu8Buf);
493}
494
495/**
496 * Queue callback for processing a queued item.
497 *
498 * @returns Success indicator.
499 * If false the item will not be removed and the flushing will stop.
500 * @param pDrvIns The driver instance.
501 * @param pItemCore Pointer to the queue item to process.
502 */
503static DECLCALLBACK(bool) drvNATQueueConsumer(PPDMDRVINS pDrvIns, PPDMQUEUEITEMCORE pItemCore)
504{
505 PDRVNAT pThis = PDMINS_2_DATA(pDrvIns, PDRVNAT);
506 PDRVNATQUEUITEM pItem = (PDRVNATQUEUITEM)pItemCore;
507 PRTREQ pReq = NULL;
508 Log(("drvNATQueueConsumer(pItem:%p, pu8Buf:%p, cb:%d)\n", pItem, pItem->pu8Buf, pItem->cb));
509 Log2(("drvNATQueueConsumer: pu8Buf:\n%.Rhxd\n", pItem->pu8Buf));
510 int rc = pThis->pPort->pfnWaitReceiveAvail(pThis->pPort, 0);
511 if (RT_FAILURE(rc))
512 return false;
513 rc = pThis->pPort->pfnReceive(pThis->pPort, pItem->pu8Buf, pItem->cb);
514
515#if 0
516 rc = RTReqAlloc(pThis->pReqQueue, &pReq, RTREQTYPE_INTERNAL);
517 AssertReleaseRC(rc);
518 pReq->u.Internal.pfn = (PFNRT)slirp_post_sent;
519 pReq->u.Internal.cArgs = 2;
520 pReq->u.Internal.aArgs[0] = (uintptr_t)pThis->pNATState;
521 pReq->u.Internal.aArgs[1] = (uintptr_t)pItem->mbuf;
522 pReq->fFlags = RTREQFLAGS_VOID;
523 AssertRC(rc);
524#else
525 /*Copy buffer again, till seeking good way of syncronization with slirp mbuf management code*/
526 AssertRelease(pItem->mbuf == NULL);
527 RTMemFree((void *)pItem->pu8Buf);
528#endif
529 return RT_SUCCESS(rc);
530}
531
532/**
533 * Queries an interface to the driver.
534 *
535 * @returns Pointer to interface.
536 * @returns NULL if the interface was not supported by the driver.
537 * @param pInterface Pointer to this interface structure.
538 * @param enmInterface The requested interface identification.
539 * @thread Any thread.
540 */
541static DECLCALLBACK(void *) drvNATQueryInterface(PPDMIBASE pInterface, PDMINTERFACE enmInterface)
542{
543 PPDMDRVINS pDrvIns = PDMIBASE_2_PDMDRV(pInterface);
544 PDRVNAT pThis = PDMINS_2_DATA(pDrvIns, PDRVNAT);
545 switch (enmInterface)
546 {
547 case PDMINTERFACE_BASE:
548 return &pDrvIns->IBase;
549 case PDMINTERFACE_NETWORK_CONNECTOR:
550 return &pThis->INetworkConnector;
551 default:
552 return NULL;
553 }
554}
555
556
557/**
558 * Destruct a driver instance.
559 *
560 * Most VM resources are freed by the VM. This callback is provided so that any non-VM
561 * resources can be freed correctly.
562 *
563 * @param pDrvIns The driver instance data.
564 */
565static DECLCALLBACK(void) drvNATDestruct(PPDMDRVINS pDrvIns)
566{
567 PDRVNAT pThis = PDMINS_2_DATA(pDrvIns, PDRVNAT);
568
569 LogFlow(("drvNATDestruct:\n"));
570
571 slirp_term(pThis->pNATState);
572 pThis->pNATState = NULL;
573}
574
575
576/**
577 * Sets up the redirectors.
578 *
579 * @returns VBox status code.
580 * @param pCfgHandle The drivers configuration handle.
581 */
582static int drvNATConstructRedir(unsigned iInstance, PDRVNAT pThis, PCFGMNODE pCfgHandle, RTIPV4ADDR Network)
583{
584 /*
585 * Enumerate redirections.
586 */
587 for (PCFGMNODE pNode = CFGMR3GetFirstChild(pCfgHandle); pNode; pNode = CFGMR3GetNextChild(pNode))
588 {
589 /*
590 * Validate the port forwarding config.
591 */
592 if (!CFGMR3AreValuesValid(pNode, "Protocol\0UDP\0HostPort\0GuestPort\0GuestIP\0"))
593 return PDMDRV_SET_ERROR(pThis->pDrvIns, VERR_PDM_DRVINS_UNKNOWN_CFG_VALUES, N_("Unknown configuration in port forwarding"));
594
595 /* protocol type */
596 bool fUDP;
597 char szProtocol[32];
598 int rc = CFGMR3QueryString(pNode, "Protocol", &szProtocol[0], sizeof(szProtocol));
599 if (rc == VERR_CFGM_VALUE_NOT_FOUND)
600 {
601 rc = CFGMR3QueryBool(pNode, "UDP", &fUDP);
602 if (rc == VERR_CFGM_VALUE_NOT_FOUND)
603 fUDP = false;
604 else if (RT_FAILURE(rc))
605 return PDMDrvHlpVMSetError(pThis->pDrvIns, rc, RT_SRC_POS, N_("NAT#%d: configuration query for \"UDP\" boolean failed"), iInstance);
606 }
607 else if (RT_SUCCESS(rc))
608 {
609 if (!RTStrICmp(szProtocol, "TCP"))
610 fUDP = false;
611 else if (!RTStrICmp(szProtocol, "UDP"))
612 fUDP = true;
613 else
614 return PDMDrvHlpVMSetError(pThis->pDrvIns, VERR_INVALID_PARAMETER, RT_SRC_POS, N_("NAT#%d: Invalid configuration value for \"Protocol\": \"%s\""), iInstance, szProtocol);
615 }
616 else
617 return PDMDrvHlpVMSetError(pThis->pDrvIns, rc, RT_SRC_POS, N_("NAT#%d: configuration query for \"Protocol\" string failed"), iInstance);
618
619 /* host port */
620 int32_t iHostPort;
621 rc = CFGMR3QueryS32(pNode, "HostPort", &iHostPort);
622 if (RT_FAILURE(rc))
623 return PDMDrvHlpVMSetError(pThis->pDrvIns, rc, RT_SRC_POS, N_("NAT#%d: configuration query for \"HostPort\" integer failed"), iInstance);
624
625 /* guest port */
626 int32_t iGuestPort;
627 rc = CFGMR3QueryS32(pNode, "GuestPort", &iGuestPort);
628 if (RT_FAILURE(rc))
629 return PDMDrvHlpVMSetError(pThis->pDrvIns, rc, RT_SRC_POS, N_("NAT#%d: configuration query for \"GuestPort\" integer failed"), iInstance);
630
631 /* guest address */
632 char szGuestIP[32];
633 rc = CFGMR3QueryString(pNode, "GuestIP", &szGuestIP[0], sizeof(szGuestIP));
634 if (rc == VERR_CFGM_VALUE_NOT_FOUND)
635 RTStrPrintf(szGuestIP, sizeof(szGuestIP), "%d.%d.%d.%d",
636 (Network & 0xFF000000) >> 24, (Network & 0xFF0000) >> 16, (Network & 0xFF00) >> 8, (Network & 0xE0) | 15);
637 else if (RT_FAILURE(rc))
638 return PDMDrvHlpVMSetError(pThis->pDrvIns, rc, RT_SRC_POS, N_("NAT#%d: configuration query for \"GuestIP\" string failed"), iInstance);
639 struct in_addr GuestIP;
640 if (!inet_aton(szGuestIP, &GuestIP))
641 return PDMDrvHlpVMSetError(pThis->pDrvIns, VERR_NAT_REDIR_GUEST_IP, RT_SRC_POS,
642 N_("NAT#%d: configuration error: invalid \"GuestIP\"=\"%s\", inet_aton failed"), iInstance, szGuestIP);
643
644 /*
645 * Call slirp about it.
646 */
647 Log(("drvNATConstruct: Redir %d -> %s:%d\n", iHostPort, szGuestIP, iGuestPort));
648 if (slirp_redir(pThis->pNATState, fUDP, iHostPort, GuestIP, iGuestPort) < 0)
649 return PDMDrvHlpVMSetError(pThis->pDrvIns, VERR_NAT_REDIR_SETUP, RT_SRC_POS,
650 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);
651 } /* for each redir rule */
652
653 return VINF_SUCCESS;
654}
655
656/**
657 * Get the MAC address into the slirp stack.
658 */
659static void drvNATSetMac(PDRVNAT pThis)
660{
661 if (pThis->pConfig)
662 {
663 RTMAC Mac;
664 pThis->pConfig->pfnGetMac(pThis->pConfig, &Mac);
665 slirp_set_ethaddr(pThis->pNATState, Mac.au8);
666 }
667}
668
669
670/**
671 * After loading we have to pass the MAC address of the ethernet device to the slirp stack.
672 * Otherwise the guest is not reachable until it performs a DHCP request or an ARP request
673 * (usually done during guest boot).
674 */
675static DECLCALLBACK(int) drvNATLoadDone(PPDMDRVINS pDrvIns, PSSMHANDLE pSSMHandle)
676{
677 PDRVNAT pThis = PDMINS_2_DATA(pDrvIns, PDRVNAT);
678 drvNATSetMac(pThis);
679 return VINF_SUCCESS;
680}
681
682
683/**
684 * Some guests might not use DHCP to retrieve an IP but use a static IP.
685 */
686static DECLCALLBACK(void) drvNATPowerOn(PPDMDRVINS pDrvIns)
687{
688 PDRVNAT pThis = PDMINS_2_DATA(pDrvIns, PDRVNAT);
689 drvNATSetMac(pThis);
690}
691
692
693/**
694 * Construct a NAT network transport driver instance.
695 *
696 * @returns VBox status.
697 * @param pDrvIns The driver instance data.
698 * If the registration structure is needed, pDrvIns->pDrvReg points to it.
699 * @param pCfgHandle Configuration node handle for the driver. Use this to obtain the configuration
700 * of the driver instance. It's also found in pDrvIns->pCfgHandle, but like
701 * iInstance it's expected to be used a bit in this function.
702 */
703static DECLCALLBACK(int) drvNATConstruct(PPDMDRVINS pDrvIns, PCFGMNODE pCfgHandle)
704{
705 PDRVNAT pThis = PDMINS_2_DATA(pDrvIns, PDRVNAT);
706 char szNetAddr[16];
707 char szNetwork[32]; /* xxx.xxx.xxx.xxx/yy */
708 LogFlow(("drvNATConstruct:\n"));
709
710 /*
711 * Validate the config.
712 */
713#ifndef VBOX_WITH_SLIRP_DNS_PROXY
714 if (!CFGMR3AreValuesValid(pCfgHandle, "PassDomain\0TFTPPrefix\0BootFile\0Network\0NextServer\0"))
715#else
716 if (!CFGMR3AreValuesValid(pCfgHandle, "PassDomain\0TFTPPrefix\0BootFile\0Network\0NextServer\0DNSProxy\0"))
717#endif
718 return PDMDRV_SET_ERROR(pDrvIns, VERR_PDM_DRVINS_UNKNOWN_CFG_VALUES, N_("Unknown NAT configuration option, only supports PassDomain, TFTPPrefix, BootFile and Network"));
719
720 /*
721 * Init the static parts.
722 */
723 pThis->pDrvIns = pDrvIns;
724 pThis->pNATState = NULL;
725 pThis->pszTFTPPrefix = NULL;
726 pThis->pszBootFile = NULL;
727 pThis->pszNextServer = NULL;
728 /* IBase */
729 pDrvIns->IBase.pfnQueryInterface = drvNATQueryInterface;
730 /* INetwork */
731 pThis->INetworkConnector.pfnSend = drvNATSend;
732 pThis->INetworkConnector.pfnSetPromiscuousMode = drvNATSetPromiscuousMode;
733 pThis->INetworkConnector.pfnNotifyLinkChanged = drvNATNotifyLinkChanged;
734
735 /*
736 * Get the configuration settings.
737 */
738 bool fPassDomain = true;
739 int rc = CFGMR3QueryBool(pCfgHandle, "PassDomain", &fPassDomain);
740 if (rc == VERR_CFGM_VALUE_NOT_FOUND)
741 fPassDomain = true;
742 else if (RT_FAILURE(rc))
743 return PDMDrvHlpVMSetError(pDrvIns, rc, RT_SRC_POS, N_("NAT#%d: configuration query for \"PassDomain\" boolean failed"), pDrvIns->iInstance);
744
745 rc = CFGMR3QueryStringAlloc(pCfgHandle, "TFTPPrefix", &pThis->pszTFTPPrefix);
746 if (RT_FAILURE(rc) && rc != VERR_CFGM_VALUE_NOT_FOUND)
747 return PDMDrvHlpVMSetError(pDrvIns, rc, RT_SRC_POS, N_("NAT#%d: configuration query for \"TFTPPrefix\" string failed"), pDrvIns->iInstance);
748 rc = CFGMR3QueryStringAlloc(pCfgHandle, "BootFile", &pThis->pszBootFile);
749 if (RT_FAILURE(rc) && rc != VERR_CFGM_VALUE_NOT_FOUND)
750 return PDMDrvHlpVMSetError(pDrvIns, rc, RT_SRC_POS, N_("NAT#%d: configuration query for \"BootFile\" string failed"), pDrvIns->iInstance);
751 rc = CFGMR3QueryStringAlloc(pCfgHandle, "NextServer", &pThis->pszNextServer);
752 if (RT_FAILURE(rc) && rc != VERR_CFGM_VALUE_NOT_FOUND)
753 return PDMDrvHlpVMSetError(pDrvIns, rc, RT_SRC_POS, N_("NAT#%d: configuration query for \"NextServer\" string failed"), pDrvIns->iInstance);
754#ifdef VBOX_WITH_SLIRP_DNS_PROXY
755 int fDNSProxy;
756 rc = CFGMR3QueryS32(pCfgHandle, "DNSProxy", &fDNSProxy);
757 if (rc == VERR_CFGM_VALUE_NOT_FOUND)
758 fDNSProxy = 0;
759#endif
760
761 /*
762 * Query the network port interface.
763 */
764 pThis->pPort = (PPDMINETWORKPORT)pDrvIns->pUpBase->pfnQueryInterface(pDrvIns->pUpBase, PDMINTERFACE_NETWORK_PORT);
765 if (!pThis->pPort)
766 return PDMDRV_SET_ERROR(pDrvIns, VERR_PDM_MISSING_INTERFACE_ABOVE,
767 N_("Configuration error: the above device/driver didn't export the network port interface"));
768 pThis->pConfig = (PPDMINETWORKCONFIG)pDrvIns->pUpBase->pfnQueryInterface(pDrvIns->pUpBase, PDMINTERFACE_NETWORK_CONFIG);
769 if (!pThis->pConfig)
770 return PDMDRV_SET_ERROR(pDrvIns, VERR_PDM_MISSING_INTERFACE_ABOVE,
771 N_("Configuration error: the above device/driver didn't export the network config interface"));
772
773 /* Generate a network address for this network card. */
774 rc = CFGMR3QueryString(pCfgHandle, "Network", szNetwork, sizeof(szNetwork));
775 if (rc == VERR_CFGM_VALUE_NOT_FOUND)
776 RTStrPrintf(szNetwork, sizeof(szNetwork), "10.0.%d.0/24", pDrvIns->iInstance + 2);
777 else if (RT_FAILURE(rc))
778 return PDMDrvHlpVMSetError(pDrvIns, rc, RT_SRC_POS, N_("NAT#%d: configuration query for \"Network\" string failed"), pDrvIns->iInstance);
779
780 RTIPV4ADDR Network;
781 RTIPV4ADDR Netmask;
782 rc = RTCidrStrToIPv4(szNetwork, &Network, &Netmask);
783 if (RT_FAILURE(rc))
784 return PDMDrvHlpVMSetError(pDrvIns, rc, RT_SRC_POS, N_("NAT#%d: Configuration error: network '%s' describes not a valid IPv4 network"), pDrvIns->iInstance, szNetwork);
785
786 RTStrPrintf(szNetAddr, sizeof(szNetAddr), "%d.%d.%d.%d",
787 (Network & 0xFF000000) >> 24, (Network & 0xFF0000) >> 16, (Network & 0xFF00) >> 8, Network & 0xFF);
788
789 /*
790 * Initialize slirp.
791 */
792 rc = slirp_init(&pThis->pNATState, &szNetAddr[0], Netmask, fPassDomain, pThis);
793 if (RT_SUCCESS(rc))
794 {
795 slirp_set_dhcp_TFTP_prefix(pThis->pNATState, pThis->pszTFTPPrefix);
796 slirp_set_dhcp_TFTP_bootfile(pThis->pNATState, pThis->pszBootFile);
797 slirp_set_dhcp_next_server(pThis->pNATState, pThis->pszNextServer);
798#ifdef VBOX_WITH_SLIRP_DNS_PROXY
799 slirp_set_dhcp_dns_proxy(pThis->pNATState, fDNSProxy);
800#endif
801
802 slirp_register_timers(pThis->pNATState, pDrvIns);
803 int rc2 = drvNATConstructRedir(pDrvIns->iInstance, pThis, pCfgHandle, Network);
804 if (RT_SUCCESS(rc2))
805 {
806 /*
807 * Register a load done notification to get the MAC address into the slirp
808 * engine after we loaded a guest state.
809 */
810 rc2 = PDMDrvHlpSSMRegister(pDrvIns, pDrvIns->pDrvReg->szDriverName,
811 pDrvIns->iInstance, 0, 0,
812 NULL, NULL, NULL, NULL, NULL, drvNATLoadDone);
813 AssertRC(rc2);
814 rc = RTReqCreateQueue(&pThis->pReqQueue);
815 if (RT_FAILURE(rc))
816 {
817 LogRel(("NAT: Can't create request queue\n"));
818 return rc;
819 }
820
821 rc = PDMDrvHlpPDMQueueCreate(pDrvIns, sizeof(DRVNATQUEUITEM), 50, 0, drvNATQueueConsumer, &pThis->pSendQueue);
822 if (RT_FAILURE(rc))
823 {
824 LogRel(("NAT: Can't create send queue\n"));
825 return rc;
826 }
827
828#ifndef RT_OS_WINDOWS
829 /*
830 * Create the control pipe.
831 */
832 int fds[2];
833 if (pipe(&fds[0]) != 0) /** @todo RTPipeCreate() or something... */
834 {
835 int rc = RTErrConvertFromErrno(errno);
836 AssertRC(rc);
837 return rc;
838 }
839 pThis->PipeRead = fds[0];
840 pThis->PipeWrite = fds[1];
841#else
842 pThis->hWakeupEvent = CreateEvent(NULL, FALSE, FALSE, NULL); /* auto-reset event */
843 slirp_register_external_event(pThis->pNATState, pThis->hWakeupEvent, VBOX_WAKEUP_EVENT_INDEX);
844#endif
845
846 rc = PDMDrvHlpPDMThreadCreate(pDrvIns, &pThis->pThread, pThis, drvNATAsyncIoThread, drvNATAsyncIoWakeup, 128 * _1K, RTTHREADTYPE_IO, "NAT");
847 AssertReleaseRC(rc);
848
849#ifdef VBOX_WITH_SLIRP_MT
850 rc = PDMDrvHlpPDMThreadCreate(pDrvIns, &pThis->pGuestThread, pThis, drvNATAsyncIoGuest, drvNATAsyncIoGuestWakeup, 128 * _1K, RTTHREADTYPE_IO, "NATGUEST");
851 AssertReleaseRC(rc);
852#endif
853
854 pThis->enmLinkState = PDMNETWORKLINKSTATE_UP;
855
856 /* might return VINF_NAT_DNS */
857 return rc;
858 }
859 /* failure path */
860 rc = rc2;
861 slirp_term(pThis->pNATState);
862 pThis->pNATState = NULL;
863 }
864 else
865 {
866 PDMDRV_SET_ERROR(pDrvIns, rc, N_("Unknown error during NAT networking setup: "));
867 AssertMsgFailed(("Add error message for rc=%d (%Rrc)\n", rc, rc));
868 }
869
870 return rc;
871}
872
873
874/**
875 * NAT network transport driver registration record.
876 */
877const PDMDRVREG g_DrvNAT =
878{
879 /* u32Version */
880 PDM_DRVREG_VERSION,
881 /* szDriverName */
882 "NAT",
883 /* pszDescription */
884 "NAT Network Transport Driver",
885 /* fFlags */
886 PDM_DRVREG_FLAGS_HOST_BITS_DEFAULT,
887 /* fClass. */
888 PDM_DRVREG_CLASS_NETWORK,
889 /* cMaxInstances */
890 16,
891 /* cbInstance */
892 sizeof(DRVNAT),
893 /* pfnConstruct */
894 drvNATConstruct,
895 /* pfnDestruct */
896 drvNATDestruct,
897 /* pfnIOCtl */
898 NULL,
899 /* pfnPowerOn */
900 drvNATPowerOn,
901 /* pfnReset */
902 NULL,
903 /* pfnSuspend */
904 NULL,
905 /* pfnResume */
906 NULL,
907 /* pfnDetach */
908 NULL,
909 /* pfnPowerOff */
910 NULL
911};
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