VirtualBox

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

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

DrvNAT: missed one bit.

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