VirtualBox

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

Last change on this file since 23141 was 23141, checked in by vboxsync, 15 years ago

NAT: clean non-SLIRP_SPLIT_CAN_OUTPUT code

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