VirtualBox

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

Last change on this file since 20472 was 20457, checked in by vboxsync, 16 years ago

NAT: warnings

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