VirtualBox

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

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

NAT: cosmetics

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