VirtualBox

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

Last change on this file since 21205 was 21112, checked in by vboxsync, 15 years ago

NAT: use constant

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

© 2023 Oracle
ContactPrivacy policyTerms of Use