VirtualBox

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

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

NAT: LibAlias enabling + tcp_emu replaced with ftp_module

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