VirtualBox

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

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

DrvNAT.cpp: file header + style.

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