VirtualBox

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

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

NAT: typo (missed 'N')

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