VirtualBox

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

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

NAT: suppressing PDMQueus warning messages

  • Property svn:eol-style set to native
  • Property svn:keywords set to Author Date Id Revision
File size: 33.1 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 }
564 else
565 {
566 LogRel(("NAT: %d messages suppressed about dropping package (couldn't allocate queue item)\n", cDroppedPackets));
567 cDroppedPackets = 0;
568 }
569 RTMemFree((void *)pu8Buf);
570#endif
571}
572
573#ifdef VBOX_WITH_SIMPLIFIED_SLIRP_SYNC
574/**
575 * Queue callback for processing a queued item.
576 *
577 * @returns Success indicator.
578 * If false the item will not be removed and the flushing will stop.
579 * @param pDrvIns The driver instance.
580 * @param pItemCore Pointer to the queue item to process.
581 */
582static DECLCALLBACK(bool) drvNATQueueConsumer(PPDMDRVINS pDrvIns, PPDMQUEUEITEMCORE pItemCore)
583{
584 PDRVNAT pThis = PDMINS_2_DATA(pDrvIns, PDRVNAT);
585 PDRVNATQUEUITEM pItem = (PDRVNATQUEUITEM)pItemCore;
586 PRTREQ pReq = NULL;
587 Log(("drvNATQueueConsumer(pItem:%p, pu8Buf:%p, cb:%d)\n", pItem, pItem->pu8Buf, pItem->cb));
588 Log2(("drvNATQueueConsumer: pu8Buf:\n%.Rhxd\n", pItem->pu8Buf));
589 int rc = pThis->pPort->pfnWaitReceiveAvail(pThis->pPort, 0);
590 if (RT_FAILURE(rc))
591 return false;
592 rc = pThis->pPort->pfnReceive(pThis->pPort, pItem->pu8Buf, pItem->cb);
593
594#if 0
595 rc = RTReqAlloc(pThis->pReqQueue, &pReq, RTREQTYPE_INTERNAL);
596 AssertReleaseRC(rc);
597 pReq->u.Internal.pfn = (PFNRT)slirp_post_sent;
598 pReq->u.Internal.cArgs = 2;
599 pReq->u.Internal.aArgs[0] = (uintptr_t)pThis->pNATState;
600 pReq->u.Internal.aArgs[1] = (uintptr_t)pItem->mbuf;
601 pReq->fFlags = RTREQFLAGS_VOID;
602 AssertRC(rc);
603#else
604 /*Copy buffer again, till seeking good way of syncronization with slirp mbuf management code*/
605 AssertRelease(pItem->mbuf == NULL);
606 RTMemFree((void *)pItem->pu8Buf);
607#endif
608 return RT_SUCCESS(rc);
609}
610#endif
611
612/**
613 * Queries an interface to the driver.
614 *
615 * @returns Pointer to interface.
616 * @returns NULL if the interface was not supported by the driver.
617 * @param pInterface Pointer to this interface structure.
618 * @param enmInterface The requested interface identification.
619 * @thread Any thread.
620 */
621static DECLCALLBACK(void *) drvNATQueryInterface(PPDMIBASE pInterface, PDMINTERFACE enmInterface)
622{
623 PPDMDRVINS pDrvIns = PDMIBASE_2_PDMDRV(pInterface);
624 PDRVNAT pThis = PDMINS_2_DATA(pDrvIns, PDRVNAT);
625 switch (enmInterface)
626 {
627 case PDMINTERFACE_BASE:
628 return &pDrvIns->IBase;
629 case PDMINTERFACE_NETWORK_CONNECTOR:
630 return &pThis->INetworkConnector;
631 default:
632 return NULL;
633 }
634}
635
636
637/**
638 * Destruct a driver instance.
639 *
640 * Most VM resources are freed by the VM. This callback is provided so that any non-VM
641 * resources can be freed correctly.
642 *
643 * @param pDrvIns The driver instance data.
644 */
645static DECLCALLBACK(void) drvNATDestruct(PPDMDRVINS pDrvIns)
646{
647 PDRVNAT pThis = PDMINS_2_DATA(pDrvIns, PDRVNAT);
648
649 LogFlow(("drvNATDestruct:\n"));
650
651#ifndef VBOX_WITH_SIMPLIFIED_SLIRP_SYNC
652 int rc = RTCritSectEnter(&pThis->CritSect);
653 AssertReleaseRC(rc);
654#endif
655 slirp_term(pThis->pNATState);
656 pThis->pNATState = NULL;
657#ifndef VBOX_WITH_SIMPLIFIED_SLIRP_SYNC
658 RTCritSectLeave(&pThis->CritSect);
659 RTCritSectDelete(&pThis->CritSect);
660#endif
661}
662
663
664/**
665 * Sets up the redirectors.
666 *
667 * @returns VBox status code.
668 * @param pCfgHandle The drivers configuration handle.
669 */
670static int drvNATConstructRedir(unsigned iInstance, PDRVNAT pThis, PCFGMNODE pCfgHandle, RTIPV4ADDR Network)
671{
672 /*
673 * Enumerate redirections.
674 */
675 for (PCFGMNODE pNode = CFGMR3GetFirstChild(pCfgHandle); pNode; pNode = CFGMR3GetNextChild(pNode))
676 {
677 /*
678 * Validate the port forwarding config.
679 */
680 if (!CFGMR3AreValuesValid(pNode, "Protocol\0UDP\0HostPort\0GuestPort\0GuestIP\0"))
681 return PDMDRV_SET_ERROR(pThis->pDrvIns, VERR_PDM_DRVINS_UNKNOWN_CFG_VALUES, N_("Unknown configuration in port forwarding"));
682
683 /* protocol type */
684 bool fUDP;
685 char szProtocol[32];
686 int rc = CFGMR3QueryString(pNode, "Protocol", &szProtocol[0], sizeof(szProtocol));
687 if (rc == VERR_CFGM_VALUE_NOT_FOUND)
688 {
689 rc = CFGMR3QueryBool(pNode, "UDP", &fUDP);
690 if (rc == VERR_CFGM_VALUE_NOT_FOUND)
691 fUDP = false;
692 else if (RT_FAILURE(rc))
693 return PDMDrvHlpVMSetError(pThis->pDrvIns, rc, RT_SRC_POS, N_("NAT#%d: configuration query for \"UDP\" boolean failed"), iInstance);
694 }
695 else if (RT_SUCCESS(rc))
696 {
697 if (!RTStrICmp(szProtocol, "TCP"))
698 fUDP = false;
699 else if (!RTStrICmp(szProtocol, "UDP"))
700 fUDP = true;
701 else
702 return PDMDrvHlpVMSetError(pThis->pDrvIns, VERR_INVALID_PARAMETER, RT_SRC_POS, N_("NAT#%d: Invalid configuration value for \"Protocol\": \"%s\""), iInstance, szProtocol);
703 }
704 else
705 return PDMDrvHlpVMSetError(pThis->pDrvIns, rc, RT_SRC_POS, N_("NAT#%d: configuration query for \"Protocol\" string failed"), iInstance);
706
707 /* host port */
708 int32_t iHostPort;
709 rc = CFGMR3QueryS32(pNode, "HostPort", &iHostPort);
710 if (RT_FAILURE(rc))
711 return PDMDrvHlpVMSetError(pThis->pDrvIns, rc, RT_SRC_POS, N_("NAT#%d: configuration query for \"HostPort\" integer failed"), iInstance);
712
713 /* guest port */
714 int32_t iGuestPort;
715 rc = CFGMR3QueryS32(pNode, "GuestPort", &iGuestPort);
716 if (RT_FAILURE(rc))
717 return PDMDrvHlpVMSetError(pThis->pDrvIns, rc, RT_SRC_POS, N_("NAT#%d: configuration query for \"GuestPort\" integer failed"), iInstance);
718
719 /* guest address */
720 char szGuestIP[32];
721 rc = CFGMR3QueryString(pNode, "GuestIP", &szGuestIP[0], sizeof(szGuestIP));
722 if (rc == VERR_CFGM_VALUE_NOT_FOUND)
723 RTStrPrintf(szGuestIP, sizeof(szGuestIP), "%d.%d.%d.%d",
724 (Network & 0xFF000000) >> 24, (Network & 0xFF0000) >> 16, (Network & 0xFF00) >> 8, (Network & 0xE0) | 15);
725 else if (RT_FAILURE(rc))
726 return PDMDrvHlpVMSetError(pThis->pDrvIns, rc, RT_SRC_POS, N_("NAT#%d: configuration query for \"GuestIP\" string failed"), iInstance);
727 struct in_addr GuestIP;
728 if (!inet_aton(szGuestIP, &GuestIP))
729 return PDMDrvHlpVMSetError(pThis->pDrvIns, VERR_NAT_REDIR_GUEST_IP, RT_SRC_POS,
730 N_("NAT#%d: configuration error: invalid \"GuestIP\"=\"%s\", inet_aton failed"), iInstance, szGuestIP);
731
732 /*
733 * Call slirp about it.
734 */
735 Log(("drvNATConstruct: Redir %d -> %s:%d\n", iHostPort, szGuestIP, iGuestPort));
736 if (slirp_redir(pThis->pNATState, fUDP, iHostPort, GuestIP, iGuestPort) < 0)
737 return PDMDrvHlpVMSetError(pThis->pDrvIns, VERR_NAT_REDIR_SETUP, RT_SRC_POS,
738 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);
739 } /* for each redir rule */
740
741 return VINF_SUCCESS;
742}
743
744/**
745 * Get the MAC address into the slirp stack.
746 */
747static void drvNATSetMac(PDRVNAT pThis)
748{
749 if (pThis->pConfig)
750 {
751 RTMAC Mac;
752 pThis->pConfig->pfnGetMac(pThis->pConfig, &Mac);
753 slirp_set_ethaddr(pThis->pNATState, Mac.au8);
754 }
755}
756
757
758/**
759 * After loading we have to pass the MAC address of the ethernet device to the slirp stack.
760 * Otherwise the guest is not reachable until it performs a DHCP request or an ARP request
761 * (usually done during guest boot).
762 */
763static DECLCALLBACK(int) drvNATLoadDone(PPDMDRVINS pDrvIns, PSSMHANDLE pSSMHandle)
764{
765 PDRVNAT pThis = PDMINS_2_DATA(pDrvIns, PDRVNAT);
766 drvNATSetMac(pThis);
767 return VINF_SUCCESS;
768}
769
770
771/**
772 * Some guests might not use DHCP to retrieve an IP but use a static IP.
773 */
774static DECLCALLBACK(void) drvNATPowerOn(PPDMDRVINS pDrvIns)
775{
776 PDRVNAT pThis = PDMINS_2_DATA(pDrvIns, PDRVNAT);
777 drvNATSetMac(pThis);
778}
779
780
781/**
782 * Construct a NAT network transport driver instance.
783 *
784 * @returns VBox status.
785 * @param pDrvIns The driver instance data.
786 * If the registration structure is needed, pDrvIns->pDrvReg points to it.
787 * @param pCfgHandle Configuration node handle for the driver. Use this to obtain the configuration
788 * of the driver instance. It's also found in pDrvIns->pCfgHandle, but like
789 * iInstance it's expected to be used a bit in this function.
790 */
791static DECLCALLBACK(int) drvNATConstruct(PPDMDRVINS pDrvIns, PCFGMNODE pCfgHandle)
792{
793 PDRVNAT pThis = PDMINS_2_DATA(pDrvIns, PDRVNAT);
794 char szNetAddr[16];
795 char szNetwork[32]; /* xxx.xxx.xxx.xxx/yy */
796 LogFlow(("drvNATConstruct:\n"));
797
798 /*
799 * Validate the config.
800 */
801 if (!CFGMR3AreValuesValid(pCfgHandle, "PassDomain\0TFTPPrefix\0BootFile\0Network\0"))
802 return PDMDRV_SET_ERROR(pDrvIns, VERR_PDM_DRVINS_UNKNOWN_CFG_VALUES, N_("Unknown NAT configuration option, only supports PassDomain, TFTPPrefix, BootFile and Network"));
803
804 /*
805 * Init the static parts.
806 */
807 pThis->pDrvIns = pDrvIns;
808 pThis->pNATState = NULL;
809 pThis->pszTFTPPrefix = NULL;
810 pThis->pszBootFile = NULL;
811 /* IBase */
812 pDrvIns->IBase.pfnQueryInterface = drvNATQueryInterface;
813 /* INetwork */
814 pThis->INetworkConnector.pfnSend = drvNATSend;
815 pThis->INetworkConnector.pfnSetPromiscuousMode = drvNATSetPromiscuousMode;
816 pThis->INetworkConnector.pfnNotifyLinkChanged = drvNATNotifyLinkChanged;
817
818 /*
819 * Get the configuration settings.
820 */
821 bool fPassDomain = true;
822 int rc = CFGMR3QueryBool(pCfgHandle, "PassDomain", &fPassDomain);
823 if (rc == VERR_CFGM_VALUE_NOT_FOUND)
824 fPassDomain = true;
825 else if (RT_FAILURE(rc))
826 return PDMDrvHlpVMSetError(pDrvIns, rc, RT_SRC_POS, N_("NAT#%d: configuration query for \"PassDomain\" boolean failed"), pDrvIns->iInstance);
827
828 rc = CFGMR3QueryStringAlloc(pCfgHandle, "TFTPPrefix", &pThis->pszTFTPPrefix);
829 if (RT_FAILURE(rc) && rc != VERR_CFGM_VALUE_NOT_FOUND)
830 return PDMDrvHlpVMSetError(pDrvIns, rc, RT_SRC_POS, N_("NAT#%d: configuration query for \"TFTPPrefix\" string failed"), pDrvIns->iInstance);
831 rc = CFGMR3QueryStringAlloc(pCfgHandle, "BootFile", &pThis->pszBootFile);
832 if (RT_FAILURE(rc) && rc != VERR_CFGM_VALUE_NOT_FOUND)
833 return PDMDrvHlpVMSetError(pDrvIns, rc, RT_SRC_POS, N_("NAT#%d: configuration query for \"BootFile\" string failed"), pDrvIns->iInstance);
834
835 /*
836 * Query the network port interface.
837 */
838 pThis->pPort = (PPDMINETWORKPORT)pDrvIns->pUpBase->pfnQueryInterface(pDrvIns->pUpBase, PDMINTERFACE_NETWORK_PORT);
839 if (!pThis->pPort)
840 return PDMDRV_SET_ERROR(pDrvIns, VERR_PDM_MISSING_INTERFACE_ABOVE,
841 N_("Configuration error: the above device/driver didn't export the network port interface"));
842 pThis->pConfig = (PPDMINETWORKCONFIG)pDrvIns->pUpBase->pfnQueryInterface(pDrvIns->pUpBase, PDMINTERFACE_NETWORK_CONFIG);
843 if (!pThis->pConfig)
844 return PDMDRV_SET_ERROR(pDrvIns, VERR_PDM_MISSING_INTERFACE_ABOVE,
845 N_("Configuration error: the above device/driver didn't export the network config interface"));
846
847 /* Generate a network address for this network card. */
848 rc = CFGMR3QueryString(pCfgHandle, "Network", szNetwork, sizeof(szNetwork));
849 if (rc == VERR_CFGM_VALUE_NOT_FOUND)
850 RTStrPrintf(szNetwork, sizeof(szNetwork), "10.0.%d.0/24", pDrvIns->iInstance + 2);
851 else if (RT_FAILURE(rc))
852 return PDMDrvHlpVMSetError(pDrvIns, rc, RT_SRC_POS, N_("NAT#%d: configuration query for \"Network\" string failed"), pDrvIns->iInstance);
853
854 RTIPV4ADDR Network;
855 RTIPV4ADDR Netmask;
856 rc = RTCidrStrToIPv4(szNetwork, &Network, &Netmask);
857 if (RT_FAILURE(rc))
858 return PDMDrvHlpVMSetError(pDrvIns, rc, RT_SRC_POS, N_("NAT#%d: Configuration error: network '%s' describes not a valid IPv4 network"), pDrvIns->iInstance, szNetwork);
859
860 RTStrPrintf(szNetAddr, sizeof(szNetAddr), "%d.%d.%d.%d",
861 (Network & 0xFF000000) >> 24, (Network & 0xFF0000) >> 16, (Network & 0xFF00) >> 8, Network & 0xFF);
862
863 /*
864 * The slirp lock..
865 */
866#ifndef VBOX_WITH_SIMPLIFIED_SLIRP_SYNC
867 rc = RTCritSectInit(&pThis->CritSect);
868 if (RT_FAILURE(rc))
869 return rc;
870#endif
871 /*
872 * Initialize slirp.
873 */
874 rc = slirp_init(&pThis->pNATState, &szNetAddr[0], Netmask, fPassDomain, pThis->pszTFTPPrefix, pThis->pszBootFile, pThis);
875 if (RT_SUCCESS(rc))
876 {
877 slirp_register_timers(pThis->pNATState, pDrvIns);
878 int rc2 = drvNATConstructRedir(pDrvIns->iInstance, pThis, pCfgHandle, Network);
879 if (RT_SUCCESS(rc2))
880 {
881 /*
882 * Register a load done notification to get the MAC address into the slirp
883 * engine after we loaded a guest state.
884 */
885 rc2 = PDMDrvHlpSSMRegister(pDrvIns, pDrvIns->pDrvReg->szDriverName,
886 pDrvIns->iInstance, 0, 0,
887 NULL, NULL, NULL, NULL, NULL, drvNATLoadDone);
888 AssertRC(rc2);
889#ifndef VBOX_WITH_SIMPLIFIED_SLIRP_SYNC
890 pDrvIns->pDrvHlp->pfnPDMPollerRegister(pDrvIns, drvNATPoller);
891#else
892 rc = RTReqCreateQueue(&pThis->pReqQueue);
893 if (RT_FAILURE(rc))
894 {
895 LogRel(("NAT: Can't create request queue\n"));
896 return rc;
897 }
898
899 rc = PDMDrvHlpPDMQueueCreate(pDrvIns, sizeof(DRVNATQUEUITEM), 50, 0, drvNATQueueConsumer, &pThis->pSendQueue);
900 if (RT_FAILURE(rc))
901 {
902 LogRel(("NAT: Can't create send queue\n"));
903 return rc;
904 }
905
906# ifndef RT_OS_WINDOWS
907 /*
908 * Create the control pipe.
909 */
910 int fds[2];
911 if (pipe(&fds[0]) != 0) /** @todo RTPipeCreate() or something... */
912 {
913 int rc = RTErrConvertFromErrno(errno);
914 AssertRC(rc);
915 return rc;
916 }
917 pThis->PipeRead = fds[0];
918 pThis->PipeWrite = fds[1];
919# else
920 pThis->hWakeupEvent = CreateEvent(NULL, FALSE, FALSE, NULL); /* auto-reset event */
921 slirp_register_external_event(pThis->pNATState, pThis->hWakeupEvent, VBOX_WAKEUP_EVENT_INDEX);
922# endif
923
924 rc = PDMDrvHlpPDMThreadCreate(pDrvIns, &pThis->pThread, pThis, drvNATAsyncIoThread, drvNATAsyncIoWakeup, 128 * _1K, RTTHREADTYPE_IO, "NAT");
925 AssertReleaseRC(rc);
926
927#ifdef VBOX_WITH_SLIRP_MT
928 rc = PDMDrvHlpPDMThreadCreate(pDrvIns, &pThis->pGuestThread, pThis, drvNATAsyncIoGuest, drvNATAsyncIoGuestWakeup, 128 * _1K, RTTHREADTYPE_IO, "NATGUEST");
929 AssertReleaseRC(rc);
930#endif
931#endif
932
933 pThis->enmLinkState = PDMNETWORKLINKSTATE_UP;
934
935 /* might return VINF_NAT_DNS */
936 return rc;
937 }
938 /* failure path */
939 rc = rc2;
940 slirp_term(pThis->pNATState);
941 pThis->pNATState = NULL;
942 }
943 else
944 {
945 PDMDRV_SET_ERROR(pDrvIns, rc, N_("Unknown error during NAT networking setup: "));
946 AssertMsgFailed(("Add error message for rc=%d (%Rrc)\n", rc, rc));
947 }
948
949#ifndef VBOX_WITH_SIMPLIFIED_SLIRP_SYNC
950 RTCritSectDelete(&pThis->CritSect);
951#endif
952 return rc;
953}
954
955
956/**
957 * NAT network transport driver registration record.
958 */
959const PDMDRVREG g_DrvNAT =
960{
961 /* u32Version */
962 PDM_DRVREG_VERSION,
963 /* szDriverName */
964 "NAT",
965 /* pszDescription */
966 "NAT Network Transport Driver",
967 /* fFlags */
968 PDM_DRVREG_FLAGS_HOST_BITS_DEFAULT,
969 /* fClass. */
970 PDM_DRVREG_CLASS_NETWORK,
971 /* cMaxInstances */
972 16,
973 /* cbInstance */
974 sizeof(DRVNAT),
975 /* pfnConstruct */
976 drvNATConstruct,
977 /* pfnDestruct */
978 drvNATDestruct,
979 /* pfnIOCtl */
980 NULL,
981 /* pfnPowerOn */
982 drvNATPowerOn,
983 /* pfnReset */
984 NULL,
985 /* pfnSuspend */
986 NULL,
987 /* pfnResume */
988 NULL,
989 /* pfnDetach */
990 NULL,
991 /* pfnPowerOff */
992 NULL
993};
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