VirtualBox

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

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

NAT: Process the queue unconditionally

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