VirtualBox

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

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

NAT: Network in host format

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