VirtualBox

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

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

NAT: replacing release assert with suppressed message

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