VirtualBox

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

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

NAT: DNS proxy more logging

  • Property svn:eol-style set to native
  • Property svn:keywords set to Author Date Id Revision
File size: 34.2 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# endif /* !RT_OS_WINDOWS */
354
355 LogFlow(("drvNATAsyncIoThread: pThis=%p\n", pThis));
356
357 if (pThread->enmState == PDMTHREADSTATE_INITIALIZING)
358 return VINF_SUCCESS;
359
360# ifdef RT_OS_WINDOWS
361 phEvents = slirp_get_events(pThis->pNATState);
362# endif /* RT_OS_WINDOWS */
363
364 /*
365 * Polling loop.
366 */
367 while (pThread->enmState == PDMTHREADSTATE_RUNNING)
368 {
369 nFDs = -1;
370
371 /*
372 * To prevent concurent execution of sending/receving threads
373 */
374# ifndef RT_OS_WINDOWS
375 nFDs = slirp_get_nsock(pThis->pNATState);
376 polls = NULL;
377 polls = (struct pollfd *)RTMemAlloc((1 + nFDs) * sizeof(struct pollfd) + sizeof(uint32_t)); /* allocation for all sockets + Management pipe*/
378 if (polls == NULL)
379 return VERR_NO_MEMORY;
380
381 slirp_select_fill(pThis->pNATState, &nFDs, &polls[1]); /*don't bother Slirp with knowelege about managemant pipe*/
382 ms = slirp_get_timeout_ms(pThis->pNATState);
383
384 polls[0].fd = pThis->PipeRead;
385 polls[0].events = POLLRDNORM|POLLPRI|POLLRDBAND; /* POLLRDBAND usually doesn't used on Linux but seems used on Solaris */
386 polls[0].revents = 0;
387
388 int cChangedFDs = poll(polls, nFDs + 1, ms ? ms : -1);
389#ifndef RT_OS_LINUX /* 2.6.23 + gdb -> hitting all the time. probably a bug in poll/ptrace/whatever. */
390 AssertRelease(cChangedFDs >= 0);
391#endif
392 if (cChangedFDs >= 0)
393 {
394 slirp_select_poll(pThis->pNATState, &polls[1], nFDs);
395 if (polls[0].revents & (POLLRDNORM|POLLPRI|POLLRDBAND))
396 {
397 /* drain the pipe */
398 char ch[1];
399 size_t cbRead;
400 int counter = 0;
401 /*
402 * drvNATSend decoupled so we don't know how many times
403 * device's thread sends before we've entered multiplex,
404 * so to avoid false alarm drain pipe here to the very end
405 *
406 * @todo: Probably we should counter drvNATSend to count how
407 * deep pipe has been filed before drain.
408 *
409 * XXX:Make it reading exactly we need to drain the pipe.
410 */
411 RTFileRead(pThis->PipeRead, &ch, 1, &cbRead);
412 }
413 /* process _all_ outstanding requests but don't wait */
414 RTReqProcess(pThis->pReqQueue, 0);
415 }
416 RTMemFree(polls);
417# else /* RT_OS_WINDOWS */
418 slirp_select_fill(pThis->pNATState, &nFDs);
419 ms = slirp_get_timeout_ms(pThis->pNATState);
420 struct timeval tv = { 0, ms*1000 };
421 event = WSAWaitForMultipleEvents(nFDs, phEvents, FALSE, ms ? ms : WSA_INFINITE, FALSE);
422 if ( (event < WSA_WAIT_EVENT_0 || event > WSA_WAIT_EVENT_0 + nFDs - 1)
423 && event != WSA_WAIT_TIMEOUT)
424 {
425 int error = WSAGetLastError();
426 LogRel(("NAT: WSAWaitForMultipleEvents returned %d (error %d)\n", event, error));
427 RTAssertReleasePanic();
428 }
429
430 if (event == WSA_WAIT_TIMEOUT)
431 {
432 /* only check for slow/fast timers */
433 slirp_select_poll(pThis->pNATState, /* fTimeout=*/true, /*fIcmp=*/false);
434 Log2(("%s: timeout\n", __FUNCTION__));
435 continue;
436 }
437
438 /* poll the sockets in any case */
439 Log2(("%s: poll\n", __FUNCTION__));
440 slirp_select_poll(pThis->pNATState, /* fTimeout=*/false, /* fIcmp=*/(event == WSA_WAIT_EVENT_0));
441 /* process _all_ outstanding requests but don't wait */
442 RTReqProcess(pThis->pReqQueue, 0);
443# ifdef VBOX_NAT_DELAY_HACK
444 if (cBreak++ > 128)
445 {
446 cBreak = 0;
447 RTThreadSleep(2);
448 }
449# endif
450# endif /* RT_OS_WINDOWS */
451 }
452
453 return VINF_SUCCESS;
454}
455
456 /**
457 * Unblock the send thread so it can respond to a state change.
458 *
459 * @returns VBox status code.
460 * @param pDevIns The pcnet device instance.
461 * @param pThread The send thread.
462 */
463static DECLCALLBACK(int) drvNATAsyncIoWakeup(PPDMDRVINS pDrvIns, PPDMTHREAD pThread)
464{
465 PDRVNAT pThis = PDMINS_2_DATA(pDrvIns, PDRVNAT);
466
467# ifndef RT_OS_WINDOWS
468 /* kick select() */
469 int rc = RTFileWrite(pThis->PipeWrite, "", 1, NULL);
470 AssertRC(rc);
471# else /* !RT_OS_WINDOWS */
472 /* kick WSAWaitForMultipleEvents() */
473 WSASetEvent(pThis->hWakeupEvent);
474# endif /* RT_OS_WINDOWS */
475
476 return VINF_SUCCESS;
477}
478
479# ifdef VBOX_WITH_SLIRP_MT
480static DECLCALLBACK(int) drvNATAsyncIoGuest(PPDMDRVINS pDrvIns, PPDMTHREAD pThread)
481{
482 PDRVNAT pThis = PDMINS_2_DATA(pDrvIns, PDRVNAT);
483 if (pThread->enmState == PDMTHREADSTATE_INITIALIZING)
484 return VINF_SUCCESS;
485 while (pThread->enmState == PDMTHREADSTATE_RUNNING)
486 {
487 slirp_process_queue(pThis->pNATState);
488 }
489 return VINF_SUCCESS;
490}
491
492static DECLCALLBACK(int) drvNATAsyncIoGuestWakeup(PPDMDRVINS pDrvIns, PPDMTHREAD pThread)
493{
494 PDRVNAT pThis = PDMINS_2_DATA(pDrvIns, PDRVNAT);
495
496 return VINF_SUCCESS;
497}
498# endif /* VBOX_WITH_SLIRP_MT */
499
500#endif /* VBOX_WITH_SIMPLIFIED_SLIRP_SYNC */
501
502
503/**
504 * Function called by slirp to check if it's possible to feed incoming data to the network port.
505 * @returns 1 if possible.
506 * @returns 0 if not possible.
507 */
508int slirp_can_output(void *pvUser)
509{
510 PDRVNAT pThis = (PDRVNAT)pvUser;
511
512 Assert(pThis);
513
514#ifndef VBOX_WITH_SIMPLIFIED_SLIRP_SYNC
515 /** Happens during termination */
516 if (!RTCritSectIsOwner(&pThis->CritSect))
517 return 0;
518
519 int rc = pThis->pPort->pfnWaitReceiveAvail(pThis->pPort, 0);
520 return RT_SUCCESS(rc);
521#else
522 return 1;
523#endif
524}
525
526
527/**
528 * Function called by slirp to feed incoming data to the network port.
529 */
530#ifdef VBOX_WITH_SIMPLIFIED_SLIRP_SYNC
531void slirp_output(void *pvUser, void *pvArg, const uint8_t *pu8Buf, int cb)
532#else
533void slirp_output(void *pvUser, const uint8_t *pu8Buf, int cb)
534#endif
535{
536 PDRVNAT pThis = (PDRVNAT)pvUser;
537
538 LogFlow(("slirp_output BEGIN %x %d\n", pu8Buf, cb));
539 Log2(("slirp_output: pu8Buf=%p cb=%#x (pThis=%p)\n%.*Rhxd\n", pu8Buf, cb, pThis, cb, pu8Buf));
540
541 Assert(pThis);
542
543#ifndef VBOX_WITH_SIMPLIFIED_SLIRP_SYNC
544 /** Happens during termination */
545 if (!RTCritSectIsOwner(&pThis->CritSect))
546 return;
547
548 int rc = pThis->pPort->pfnReceive(pThis->pPort, pu8Buf, cb);
549 AssertRC(rc);
550 LogFlow(("slirp_output END %x %d\n", pu8Buf, cb));
551#else
552
553 PDRVNATQUEUITEM pItem = (PDRVNATQUEUITEM)PDMQueueAlloc(pThis->pSendQueue);
554 if (pItem)
555 {
556 pItem->pu8Buf = pu8Buf;
557 pItem->cb = cb;
558 pItem->mbuf = pvArg;
559 Log2(("pItem:%p %.Rhxd\n", pItem, pItem->pu8Buf));
560 PDMQueueInsert(pThis->pSendQueue, &pItem->Core);
561 return;
562 }
563 static unsigned cDroppedPackets;
564 if (cDroppedPackets < 64)
565 {
566 cDroppedPackets++;
567 }
568 else
569 {
570 LogRel(("NAT: %d messages suppressed about dropping package (couldn't allocate queue item)\n", cDroppedPackets));
571 cDroppedPackets = 0;
572 }
573 RTMemFree((void *)pu8Buf);
574#endif
575}
576
577#ifdef VBOX_WITH_SIMPLIFIED_SLIRP_SYNC
578/**
579 * Queue callback for processing a queued item.
580 *
581 * @returns Success indicator.
582 * If false the item will not be removed and the flushing will stop.
583 * @param pDrvIns The driver instance.
584 * @param pItemCore Pointer to the queue item to process.
585 */
586static DECLCALLBACK(bool) drvNATQueueConsumer(PPDMDRVINS pDrvIns, PPDMQUEUEITEMCORE pItemCore)
587{
588 PDRVNAT pThis = PDMINS_2_DATA(pDrvIns, PDRVNAT);
589 PDRVNATQUEUITEM pItem = (PDRVNATQUEUITEM)pItemCore;
590 PRTREQ pReq = NULL;
591 Log(("drvNATQueueConsumer(pItem:%p, pu8Buf:%p, cb:%d)\n", pItem, pItem->pu8Buf, pItem->cb));
592 Log2(("drvNATQueueConsumer: pu8Buf:\n%.Rhxd\n", pItem->pu8Buf));
593 int rc = pThis->pPort->pfnWaitReceiveAvail(pThis->pPort, 0);
594 if (RT_FAILURE(rc))
595 return false;
596 rc = pThis->pPort->pfnReceive(pThis->pPort, pItem->pu8Buf, pItem->cb);
597
598#if 0
599 rc = RTReqAlloc(pThis->pReqQueue, &pReq, RTREQTYPE_INTERNAL);
600 AssertReleaseRC(rc);
601 pReq->u.Internal.pfn = (PFNRT)slirp_post_sent;
602 pReq->u.Internal.cArgs = 2;
603 pReq->u.Internal.aArgs[0] = (uintptr_t)pThis->pNATState;
604 pReq->u.Internal.aArgs[1] = (uintptr_t)pItem->mbuf;
605 pReq->fFlags = RTREQFLAGS_VOID;
606 AssertRC(rc);
607#else
608 /*Copy buffer again, till seeking good way of syncronization with slirp mbuf management code*/
609 AssertRelease(pItem->mbuf == NULL);
610 RTMemFree((void *)pItem->pu8Buf);
611#endif
612 return RT_SUCCESS(rc);
613}
614#endif
615
616/**
617 * Queries an interface to the driver.
618 *
619 * @returns Pointer to interface.
620 * @returns NULL if the interface was not supported by the driver.
621 * @param pInterface Pointer to this interface structure.
622 * @param enmInterface The requested interface identification.
623 * @thread Any thread.
624 */
625static DECLCALLBACK(void *) drvNATQueryInterface(PPDMIBASE pInterface, PDMINTERFACE enmInterface)
626{
627 PPDMDRVINS pDrvIns = PDMIBASE_2_PDMDRV(pInterface);
628 PDRVNAT pThis = PDMINS_2_DATA(pDrvIns, PDRVNAT);
629 switch (enmInterface)
630 {
631 case PDMINTERFACE_BASE:
632 return &pDrvIns->IBase;
633 case PDMINTERFACE_NETWORK_CONNECTOR:
634 return &pThis->INetworkConnector;
635 default:
636 return NULL;
637 }
638}
639
640
641/**
642 * Destruct a driver instance.
643 *
644 * Most VM resources are freed by the VM. This callback is provided so that any non-VM
645 * resources can be freed correctly.
646 *
647 * @param pDrvIns The driver instance data.
648 */
649static DECLCALLBACK(void) drvNATDestruct(PPDMDRVINS pDrvIns)
650{
651 PDRVNAT pThis = PDMINS_2_DATA(pDrvIns, PDRVNAT);
652
653 LogFlow(("drvNATDestruct:\n"));
654
655#ifndef VBOX_WITH_SIMPLIFIED_SLIRP_SYNC
656 int rc = RTCritSectEnter(&pThis->CritSect);
657 AssertReleaseRC(rc);
658#endif
659 slirp_term(pThis->pNATState);
660 pThis->pNATState = NULL;
661#ifndef VBOX_WITH_SIMPLIFIED_SLIRP_SYNC
662 RTCritSectLeave(&pThis->CritSect);
663 RTCritSectDelete(&pThis->CritSect);
664#endif
665}
666
667
668/**
669 * Sets up the redirectors.
670 *
671 * @returns VBox status code.
672 * @param pCfgHandle The drivers configuration handle.
673 */
674static int drvNATConstructRedir(unsigned iInstance, PDRVNAT pThis, PCFGMNODE pCfgHandle, RTIPV4ADDR Network)
675{
676 /*
677 * Enumerate redirections.
678 */
679 for (PCFGMNODE pNode = CFGMR3GetFirstChild(pCfgHandle); pNode; pNode = CFGMR3GetNextChild(pNode))
680 {
681 /*
682 * Validate the port forwarding config.
683 */
684 if (!CFGMR3AreValuesValid(pNode, "Protocol\0UDP\0HostPort\0GuestPort\0GuestIP\0"))
685 return PDMDRV_SET_ERROR(pThis->pDrvIns, VERR_PDM_DRVINS_UNKNOWN_CFG_VALUES, N_("Unknown configuration in port forwarding"));
686
687 /* protocol type */
688 bool fUDP;
689 char szProtocol[32];
690 int rc = CFGMR3QueryString(pNode, "Protocol", &szProtocol[0], sizeof(szProtocol));
691 if (rc == VERR_CFGM_VALUE_NOT_FOUND)
692 {
693 rc = CFGMR3QueryBool(pNode, "UDP", &fUDP);
694 if (rc == VERR_CFGM_VALUE_NOT_FOUND)
695 fUDP = false;
696 else if (RT_FAILURE(rc))
697 return PDMDrvHlpVMSetError(pThis->pDrvIns, rc, RT_SRC_POS, N_("NAT#%d: configuration query for \"UDP\" boolean failed"), iInstance);
698 }
699 else if (RT_SUCCESS(rc))
700 {
701 if (!RTStrICmp(szProtocol, "TCP"))
702 fUDP = false;
703 else if (!RTStrICmp(szProtocol, "UDP"))
704 fUDP = true;
705 else
706 return PDMDrvHlpVMSetError(pThis->pDrvIns, VERR_INVALID_PARAMETER, RT_SRC_POS, N_("NAT#%d: Invalid configuration value for \"Protocol\": \"%s\""), iInstance, szProtocol);
707 }
708 else
709 return PDMDrvHlpVMSetError(pThis->pDrvIns, rc, RT_SRC_POS, N_("NAT#%d: configuration query for \"Protocol\" string failed"), iInstance);
710
711 /* host port */
712 int32_t iHostPort;
713 rc = CFGMR3QueryS32(pNode, "HostPort", &iHostPort);
714 if (RT_FAILURE(rc))
715 return PDMDrvHlpVMSetError(pThis->pDrvIns, rc, RT_SRC_POS, N_("NAT#%d: configuration query for \"HostPort\" integer failed"), iInstance);
716
717 /* guest port */
718 int32_t iGuestPort;
719 rc = CFGMR3QueryS32(pNode, "GuestPort", &iGuestPort);
720 if (RT_FAILURE(rc))
721 return PDMDrvHlpVMSetError(pThis->pDrvIns, rc, RT_SRC_POS, N_("NAT#%d: configuration query for \"GuestPort\" integer failed"), iInstance);
722
723 /* guest address */
724 char szGuestIP[32];
725 rc = CFGMR3QueryString(pNode, "GuestIP", &szGuestIP[0], sizeof(szGuestIP));
726 if (rc == VERR_CFGM_VALUE_NOT_FOUND)
727 RTStrPrintf(szGuestIP, sizeof(szGuestIP), "%d.%d.%d.%d",
728 (Network & 0xFF000000) >> 24, (Network & 0xFF0000) >> 16, (Network & 0xFF00) >> 8, (Network & 0xE0) | 15);
729 else if (RT_FAILURE(rc))
730 return PDMDrvHlpVMSetError(pThis->pDrvIns, rc, RT_SRC_POS, N_("NAT#%d: configuration query for \"GuestIP\" string failed"), iInstance);
731 struct in_addr GuestIP;
732 if (!inet_aton(szGuestIP, &GuestIP))
733 return PDMDrvHlpVMSetError(pThis->pDrvIns, VERR_NAT_REDIR_GUEST_IP, RT_SRC_POS,
734 N_("NAT#%d: configuration error: invalid \"GuestIP\"=\"%s\", inet_aton failed"), iInstance, szGuestIP);
735
736 /*
737 * Call slirp about it.
738 */
739 Log(("drvNATConstruct: Redir %d -> %s:%d\n", iHostPort, szGuestIP, iGuestPort));
740 if (slirp_redir(pThis->pNATState, fUDP, iHostPort, GuestIP, iGuestPort) < 0)
741 return PDMDrvHlpVMSetError(pThis->pDrvIns, VERR_NAT_REDIR_SETUP, RT_SRC_POS,
742 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);
743 } /* for each redir rule */
744
745 return VINF_SUCCESS;
746}
747
748/**
749 * Get the MAC address into the slirp stack.
750 */
751static void drvNATSetMac(PDRVNAT pThis)
752{
753 if (pThis->pConfig)
754 {
755 RTMAC Mac;
756 pThis->pConfig->pfnGetMac(pThis->pConfig, &Mac);
757 slirp_set_ethaddr(pThis->pNATState, Mac.au8);
758 }
759}
760
761
762/**
763 * After loading we have to pass the MAC address of the ethernet device to the slirp stack.
764 * Otherwise the guest is not reachable until it performs a DHCP request or an ARP request
765 * (usually done during guest boot).
766 */
767static DECLCALLBACK(int) drvNATLoadDone(PPDMDRVINS pDrvIns, PSSMHANDLE pSSMHandle)
768{
769 PDRVNAT pThis = PDMINS_2_DATA(pDrvIns, PDRVNAT);
770 drvNATSetMac(pThis);
771 return VINF_SUCCESS;
772}
773
774
775/**
776 * Some guests might not use DHCP to retrieve an IP but use a static IP.
777 */
778static DECLCALLBACK(void) drvNATPowerOn(PPDMDRVINS pDrvIns)
779{
780 PDRVNAT pThis = PDMINS_2_DATA(pDrvIns, PDRVNAT);
781 drvNATSetMac(pThis);
782}
783
784
785/**
786 * Construct a NAT network transport driver instance.
787 *
788 * @returns VBox status.
789 * @param pDrvIns The driver instance data.
790 * If the registration structure is needed, pDrvIns->pDrvReg points to it.
791 * @param pCfgHandle Configuration node handle for the driver. Use this to obtain the configuration
792 * of the driver instance. It's also found in pDrvIns->pCfgHandle, but like
793 * iInstance it's expected to be used a bit in this function.
794 */
795static DECLCALLBACK(int) drvNATConstruct(PPDMDRVINS pDrvIns, PCFGMNODE pCfgHandle)
796{
797 PDRVNAT pThis = PDMINS_2_DATA(pDrvIns, PDRVNAT);
798 char szNetAddr[16];
799 char szNetwork[32]; /* xxx.xxx.xxx.xxx/yy */
800 LogFlow(("drvNATConstruct:\n"));
801
802 /*
803 * Validate the config.
804 */
805#ifndef VBOX_WITH_SLIRP_DNS_PROXY
806 if (!CFGMR3AreValuesValid(pCfgHandle, "PassDomain\0TFTPPrefix\0BootFile\0Network\0NextServer\0"))
807#else
808 if (!CFGMR3AreValuesValid(pCfgHandle, "PassDomain\0TFTPPrefix\0BootFile\0Network\0NextServer\0DNSProxy\0"))
809#endif
810 return PDMDRV_SET_ERROR(pDrvIns, VERR_PDM_DRVINS_UNKNOWN_CFG_VALUES, N_("Unknown NAT configuration option, only supports PassDomain, TFTPPrefix, BootFile and Network"));
811
812 /*
813 * Init the static parts.
814 */
815 pThis->pDrvIns = pDrvIns;
816 pThis->pNATState = NULL;
817 pThis->pszTFTPPrefix = NULL;
818 pThis->pszBootFile = NULL;
819 pThis->pszNextServer = NULL;
820 /* IBase */
821 pDrvIns->IBase.pfnQueryInterface = drvNATQueryInterface;
822 /* INetwork */
823 pThis->INetworkConnector.pfnSend = drvNATSend;
824 pThis->INetworkConnector.pfnSetPromiscuousMode = drvNATSetPromiscuousMode;
825 pThis->INetworkConnector.pfnNotifyLinkChanged = drvNATNotifyLinkChanged;
826
827 /*
828 * Get the configuration settings.
829 */
830 bool fPassDomain = true;
831 int rc = CFGMR3QueryBool(pCfgHandle, "PassDomain", &fPassDomain);
832 if (rc == VERR_CFGM_VALUE_NOT_FOUND)
833 fPassDomain = true;
834 else if (RT_FAILURE(rc))
835 return PDMDrvHlpVMSetError(pDrvIns, rc, RT_SRC_POS, N_("NAT#%d: configuration query for \"PassDomain\" boolean failed"), pDrvIns->iInstance);
836
837 rc = CFGMR3QueryStringAlloc(pCfgHandle, "TFTPPrefix", &pThis->pszTFTPPrefix);
838 if (RT_FAILURE(rc) && rc != VERR_CFGM_VALUE_NOT_FOUND)
839 return PDMDrvHlpVMSetError(pDrvIns, rc, RT_SRC_POS, N_("NAT#%d: configuration query for \"TFTPPrefix\" string failed"), pDrvIns->iInstance);
840 rc = CFGMR3QueryStringAlloc(pCfgHandle, "BootFile", &pThis->pszBootFile);
841 if (RT_FAILURE(rc) && rc != VERR_CFGM_VALUE_NOT_FOUND)
842 return PDMDrvHlpVMSetError(pDrvIns, rc, RT_SRC_POS, N_("NAT#%d: configuration query for \"BootFile\" string failed"), pDrvIns->iInstance);
843 rc = CFGMR3QueryStringAlloc(pCfgHandle, "NextServer", &pThis->pszNextServer);
844 if (RT_FAILURE(rc) && rc != VERR_CFGM_VALUE_NOT_FOUND)
845 return PDMDrvHlpVMSetError(pDrvIns, rc, RT_SRC_POS, N_("NAT#%d: configuration query for \"NextServer\" string failed"), pDrvIns->iInstance);
846#ifdef VBOX_WITH_SLIRP_DNS_PROXY
847 int fDNSProxy;
848 rc = CFGMR3QueryS32(pCfgHandle, "DNSProxy", &fDNSProxy);
849 if (rc == VERR_CFGM_VALUE_NOT_FOUND)
850 fDNSProxy = 0;
851#endif
852
853 /*
854 * Query the network port interface.
855 */
856 pThis->pPort = (PPDMINETWORKPORT)pDrvIns->pUpBase->pfnQueryInterface(pDrvIns->pUpBase, PDMINTERFACE_NETWORK_PORT);
857 if (!pThis->pPort)
858 return PDMDRV_SET_ERROR(pDrvIns, VERR_PDM_MISSING_INTERFACE_ABOVE,
859 N_("Configuration error: the above device/driver didn't export the network port interface"));
860 pThis->pConfig = (PPDMINETWORKCONFIG)pDrvIns->pUpBase->pfnQueryInterface(pDrvIns->pUpBase, PDMINTERFACE_NETWORK_CONFIG);
861 if (!pThis->pConfig)
862 return PDMDRV_SET_ERROR(pDrvIns, VERR_PDM_MISSING_INTERFACE_ABOVE,
863 N_("Configuration error: the above device/driver didn't export the network config interface"));
864
865 /* Generate a network address for this network card. */
866 rc = CFGMR3QueryString(pCfgHandle, "Network", szNetwork, sizeof(szNetwork));
867 if (rc == VERR_CFGM_VALUE_NOT_FOUND)
868 RTStrPrintf(szNetwork, sizeof(szNetwork), "10.0.%d.0/24", pDrvIns->iInstance + 2);
869 else if (RT_FAILURE(rc))
870 return PDMDrvHlpVMSetError(pDrvIns, rc, RT_SRC_POS, N_("NAT#%d: configuration query for \"Network\" string failed"), pDrvIns->iInstance);
871
872 RTIPV4ADDR Network;
873 RTIPV4ADDR Netmask;
874 rc = RTCidrStrToIPv4(szNetwork, &Network, &Netmask);
875 if (RT_FAILURE(rc))
876 return PDMDrvHlpVMSetError(pDrvIns, rc, RT_SRC_POS, N_("NAT#%d: Configuration error: network '%s' describes not a valid IPv4 network"), pDrvIns->iInstance, szNetwork);
877
878 RTStrPrintf(szNetAddr, sizeof(szNetAddr), "%d.%d.%d.%d",
879 (Network & 0xFF000000) >> 24, (Network & 0xFF0000) >> 16, (Network & 0xFF00) >> 8, Network & 0xFF);
880
881 /*
882 * The slirp lock..
883 */
884#ifndef VBOX_WITH_SIMPLIFIED_SLIRP_SYNC
885 rc = RTCritSectInit(&pThis->CritSect);
886 if (RT_FAILURE(rc))
887 return rc;
888#endif
889 /*
890 * Initialize slirp.
891 */
892 rc = slirp_init(&pThis->pNATState, &szNetAddr[0], Netmask, fPassDomain, pThis);
893 if (RT_SUCCESS(rc))
894 {
895 slirp_set_dhcp_TFTP_prefix(pThis->pNATState, pThis->pszTFTPPrefix);
896 slirp_set_dhcp_TFTP_bootfile(pThis->pNATState, pThis->pszBootFile);
897 slirp_set_dhcp_next_server(pThis->pNATState, pThis->pszNextServer);
898#ifdef VBOX_WITH_SLIRP_DNS_PROXY
899 slirp_set_dhcp_dns_proxy(pThis->pNATState, fDNSProxy);
900#endif
901
902 slirp_register_timers(pThis->pNATState, pDrvIns);
903 int rc2 = drvNATConstructRedir(pDrvIns->iInstance, pThis, pCfgHandle, Network);
904 if (RT_SUCCESS(rc2))
905 {
906 /*
907 * Register a load done notification to get the MAC address into the slirp
908 * engine after we loaded a guest state.
909 */
910 rc2 = PDMDrvHlpSSMRegister(pDrvIns, pDrvIns->pDrvReg->szDriverName,
911 pDrvIns->iInstance, 0, 0,
912 NULL, NULL, NULL, NULL, NULL, drvNATLoadDone);
913 AssertRC(rc2);
914#ifndef VBOX_WITH_SIMPLIFIED_SLIRP_SYNC
915 pDrvIns->pDrvHlp->pfnPDMPollerRegister(pDrvIns, drvNATPoller);
916#else
917 rc = RTReqCreateQueue(&pThis->pReqQueue);
918 if (RT_FAILURE(rc))
919 {
920 LogRel(("NAT: Can't create request queue\n"));
921 return rc;
922 }
923
924 rc = PDMDrvHlpPDMQueueCreate(pDrvIns, sizeof(DRVNATQUEUITEM), 50, 0, drvNATQueueConsumer, &pThis->pSendQueue);
925 if (RT_FAILURE(rc))
926 {
927 LogRel(("NAT: Can't create send queue\n"));
928 return rc;
929 }
930
931# ifndef RT_OS_WINDOWS
932 /*
933 * Create the control pipe.
934 */
935 int fds[2];
936 if (pipe(&fds[0]) != 0) /** @todo RTPipeCreate() or something... */
937 {
938 int rc = RTErrConvertFromErrno(errno);
939 AssertRC(rc);
940 return rc;
941 }
942 pThis->PipeRead = fds[0];
943 pThis->PipeWrite = fds[1];
944# else
945 pThis->hWakeupEvent = CreateEvent(NULL, FALSE, FALSE, NULL); /* auto-reset event */
946 slirp_register_external_event(pThis->pNATState, pThis->hWakeupEvent, VBOX_WAKEUP_EVENT_INDEX);
947# endif
948
949 rc = PDMDrvHlpPDMThreadCreate(pDrvIns, &pThis->pThread, pThis, drvNATAsyncIoThread, drvNATAsyncIoWakeup, 128 * _1K, RTTHREADTYPE_IO, "NAT");
950 AssertReleaseRC(rc);
951
952#ifdef VBOX_WITH_SLIRP_MT
953 rc = PDMDrvHlpPDMThreadCreate(pDrvIns, &pThis->pGuestThread, pThis, drvNATAsyncIoGuest, drvNATAsyncIoGuestWakeup, 128 * _1K, RTTHREADTYPE_IO, "NATGUEST");
954 AssertReleaseRC(rc);
955#endif
956#endif
957
958 pThis->enmLinkState = PDMNETWORKLINKSTATE_UP;
959
960 /* might return VINF_NAT_DNS */
961 return rc;
962 }
963 /* failure path */
964 rc = rc2;
965 slirp_term(pThis->pNATState);
966 pThis->pNATState = NULL;
967 }
968 else
969 {
970 PDMDRV_SET_ERROR(pDrvIns, rc, N_("Unknown error during NAT networking setup: "));
971 AssertMsgFailed(("Add error message for rc=%d (%Rrc)\n", rc, rc));
972 }
973
974
975#ifndef VBOX_WITH_SIMPLIFIED_SLIRP_SYNC
976 RTCritSectDelete(&pThis->CritSect);
977#endif
978 return rc;
979}
980
981
982/**
983 * NAT network transport driver registration record.
984 */
985const PDMDRVREG g_DrvNAT =
986{
987 /* u32Version */
988 PDM_DRVREG_VERSION,
989 /* szDriverName */
990 "NAT",
991 /* pszDescription */
992 "NAT Network Transport Driver",
993 /* fFlags */
994 PDM_DRVREG_FLAGS_HOST_BITS_DEFAULT,
995 /* fClass. */
996 PDM_DRVREG_CLASS_NETWORK,
997 /* cMaxInstances */
998 16,
999 /* cbInstance */
1000 sizeof(DRVNAT),
1001 /* pfnConstruct */
1002 drvNATConstruct,
1003 /* pfnDestruct */
1004 drvNATDestruct,
1005 /* pfnIOCtl */
1006 NULL,
1007 /* pfnPowerOn */
1008 drvNATPowerOn,
1009 /* pfnReset */
1010 NULL,
1011 /* pfnSuspend */
1012 NULL,
1013 /* pfnResume */
1014 NULL,
1015 /* pfnDetach */
1016 NULL,
1017 /* pfnPowerOff */
1018 NULL
1019};
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