VirtualBox

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

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

Automated rebranding to Oracle copyright/license strings via filemuncher

  • Property svn:eol-style set to native
  • Property svn:keywords set to Author Date Id Revision
File size: 46.2 KB
Line 
1/* $Id: DrvNAT.cpp 28800 2010-04-27 08:22:32Z vboxsync $ */
2/** @file
3 * DrvNAT - NAT network transport driver.
4 */
5
6/*
7 * Copyright (C) 2006-2010 Oracle Corporation
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
18
19/*******************************************************************************
20* Header Files *
21*******************************************************************************/
22#define LOG_GROUP LOG_GROUP_DRV_NAT
23#define __STDC_LIMIT_MACROS
24#define __STDC_CONSTANT_MACROS
25#include "slirp/libslirp.h"
26#include "slirp/ctl.h"
27#include <VBox/pdmdrv.h>
28#include <VBox/pdmnetifs.h>
29#include <VBox/pdmnetinline.h>
30#include <iprt/assert.h>
31#include <iprt/file.h>
32#include <iprt/mem.h>
33#include <iprt/string.h>
34#include <iprt/critsect.h>
35#include <iprt/cidr.h>
36#include <iprt/stream.h>
37#include <iprt/uuid.h>
38
39#include "Builtins.h"
40
41#ifndef RT_OS_WINDOWS
42# include <unistd.h>
43# include <fcntl.h>
44# include <poll.h>
45# include <errno.h>
46#endif
47#ifdef RT_OS_FREEBSD
48# include <netinet/in.h>
49#endif
50#include <iprt/semaphore.h>
51#include <iprt/req.h>
52
53#define COUNTERS_INIT
54#include "counters.h"
55
56
57/*******************************************************************************
58* Defined Constants And Macros *
59*******************************************************************************/
60
61/**
62 * @todo: This is a bad hack to prevent freezing the guest during high network
63 * activity. Windows host only. This needs to be fixed properly.
64 */
65#define VBOX_NAT_DELAY_HACK
66
67#define GET_EXTRADATA(pthis, node, name, rc, type, type_name, var) \
68do { \
69 (rc) = CFGMR3Query ## type((node), name, &(var)); \
70 if (RT_FAILURE((rc)) && (rc) != VERR_CFGM_VALUE_NOT_FOUND) \
71 return PDMDrvHlpVMSetError((pthis)->pDrvIns, (rc), RT_SRC_POS, N_("NAT#%d: configuration query for \""name"\" " #type_name " failed"), \
72 (pthis)->pDrvIns->iInstance); \
73} while (0)
74
75#define GET_ED_STRICT(pthis, node, name, rc, type, type_name, var) \
76do { \
77 (rc) = CFGMR3Query ## type((node), name, &(var)); \
78 if (RT_FAILURE((rc))) \
79 return PDMDrvHlpVMSetError((pthis)->pDrvIns, (rc), RT_SRC_POS, N_("NAT#%d: configuration query for \""name"\" " #type_name " failed"), \
80 (pthis)->pDrvIns->iInstance); \
81} while (0)
82
83#define GET_EXTRADATA_N(pthis, node, name, rc, type, type_name, var, var_size) \
84do { \
85 (rc) = CFGMR3Query ## type((node), name, &(var), var_size); \
86 if (RT_FAILURE((rc)) && (rc) != VERR_CFGM_VALUE_NOT_FOUND) \
87 return PDMDrvHlpVMSetError((pthis)->pDrvIns, (rc), RT_SRC_POS, N_("NAT#%d: configuration query for \""name"\" " #type_name " failed"), \
88 (pthis)->pDrvIns->iInstance); \
89} while (0)
90
91#define GET_BOOL(rc, pthis, node, name, var) \
92 GET_EXTRADATA(pthis, node, name, (rc), Bool, bolean, (var))
93#define GET_STRING(rc, pthis, node, name, var, var_size) \
94 GET_EXTRADATA_N(pthis, node, name, (rc), String, string, (var), (var_size))
95#define GET_STRING_ALLOC(rc, pthis, node, name, var) \
96 GET_EXTRADATA(pthis, node, name, (rc), StringAlloc, string, (var))
97#define GET_S32(rc, pthis, node, name, var) \
98 GET_EXTRADATA(pthis, node, name, (rc), S32, int, (var))
99#define GET_S32_STRICT(rc, pthis, node, name, var) \
100 GET_ED_STRICT(pthis, node, name, (rc), S32, int, (var))
101
102
103
104#define DO_GET_IP(rc, node, instance, status, x) \
105do { \
106 char sz##x[32]; \
107 GET_STRING((rc), (node), (instance), #x, sz ## x[0], sizeof(sz ## x)); \
108 if (rc != VERR_CFGM_VALUE_NOT_FOUND) \
109 (status) = inet_aton(sz ## x, &x); \
110} while (0)
111
112#define GETIP_DEF(rc, node, instance, x, def) \
113do \
114{ \
115 int status = 0; \
116 DO_GET_IP((rc), (node), (instance), status, x); \
117 if (status == 0 || rc == VERR_CFGM_VALUE_NOT_FOUND) \
118 x.s_addr = def; \
119} while (0)
120
121/*******************************************************************************
122* Structures and Typedefs *
123*******************************************************************************/
124/**
125 * NAT network transport driver instance data.
126 *
127 * @implements PDMINETWORKUP
128 */
129typedef struct DRVNAT
130{
131 /** The network interface. */
132 PDMINETWORKUP INetworkUp;
133 /** The port we're attached to. */
134 PPDMINETWORKDOWN pIAboveNet;
135 /** The network config of the port we're attached to. */
136 PPDMINETWORKCONFIG pIAboveConfig;
137 /** Pointer to the driver instance. */
138 PPDMDRVINS pDrvIns;
139 /** Link state */
140 PDMNETWORKLINKSTATE enmLinkState;
141 /** NAT state for this instance. */
142 PNATState pNATState;
143 /** TFTP directory prefix. */
144 char *pszTFTPPrefix;
145 /** Boot file name to provide in the DHCP server response. */
146 char *pszBootFile;
147 /** tftp server name to provide in the DHCP server response. */
148 char *pszNextServer;
149 /** Polling thread. */
150 PPDMTHREAD pSlirpThread;
151 /** Queue for NAT-thread-external events. */
152 PRTREQQUEUE pSlirpReqQueue;
153 /** The guest IP for port-forwarding. */
154 uint32_t GuestIP;
155 uint32_t alignment1;
156
157#ifdef VBOX_WITH_SLIRP_MT
158 PPDMTHREAD pGuestThread;
159#endif
160#ifndef RT_OS_WINDOWS
161 /** The write end of the control pipe. */
162 RTFILE PipeWrite;
163 /** The read end of the control pipe. */
164 RTFILE PipeRead;
165# if HC_ARCH_BITS == 32
166 /** Alignment padding. */
167 uint32_t alignment2;
168# endif
169#else
170 /** for external notification */
171 HANDLE hWakeupEvent;
172#endif
173
174#define DRV_PROFILE_COUNTER(name, dsc) STAMPROFILE Stat ## name
175#define DRV_COUNTING_COUNTER(name, dsc) STAMCOUNTER Stat ## name
176#include "counters.h"
177 /** thread delivering packets for receiving by the guest */
178 PPDMTHREAD pRecvThread;
179 /** thread delivering urg packets for receiving by the guest */
180 PPDMTHREAD pUrgRecvThread;
181 /** event to wakeup the guest receive thread */
182 RTSEMEVENT EventRecv;
183 /** event to wakeup the guest urgent receive thread */
184 RTSEMEVENT EventUrgRecv;
185 /** Receive Req queue (deliver packets to the guest) */
186 PRTREQQUEUE pRecvReqQueue;
187 /** Receive Urgent Req queue (deliver packets to the guest). */
188 PRTREQQUEUE pUrgRecvReqQueue;
189
190 /** makes access to device func RecvAvail and Recv atomical. */
191 RTCRITSECT DevAccessLock;
192 /** Number of in-flight urgent packets. */
193 volatile uint32_t cUrgPkts;
194 /** Number of in-flight regular packets. */
195 volatile uint32_t cPkts;
196
197 /** Transmit lock taken by BeginXmit and released by EndXmit. */
198 RTCRITSECT XmitLock;
199} DRVNAT;
200AssertCompileMemberAlignment(DRVNAT, StatNATRecvWakeups, 8);
201/** Pointer the NAT driver instance data. */
202typedef DRVNAT *PDRVNAT;
203
204
205/*******************************************************************************
206* Internal Functions *
207*******************************************************************************/
208static void drvNATNotifyNATThread(PDRVNAT pThis, const char *pszWho);
209
210
211static DECLCALLBACK(int) drvNATRecv(PPDMDRVINS pDrvIns, PPDMTHREAD pThread)
212{
213 PDRVNAT pThis = PDMINS_2_DATA(pDrvIns, PDRVNAT);
214
215 if (pThread->enmState == PDMTHREADSTATE_INITIALIZING)
216 return VINF_SUCCESS;
217
218 while (pThread->enmState == PDMTHREADSTATE_RUNNING)
219 {
220 RTReqProcess(pThis->pRecvReqQueue, 0);
221 if (ASMAtomicReadU32(&pThis->cPkts) == 0)
222 RTSemEventWait(pThis->EventRecv, RT_INDEFINITE_WAIT);
223 }
224 return VINF_SUCCESS;
225}
226
227
228static DECLCALLBACK(int) drvNATRecvWakeup(PPDMDRVINS pDrvIns, PPDMTHREAD pThread)
229{
230 PDRVNAT pThis = PDMINS_2_DATA(pDrvIns, PDRVNAT);
231 int rc;
232 rc = RTSemEventSignal(pThis->EventRecv);
233
234 STAM_COUNTER_INC(&pThis->StatNATRecvWakeups);
235 return VINF_SUCCESS;
236}
237
238static DECLCALLBACK(int) drvNATUrgRecv(PPDMDRVINS pDrvIns, PPDMTHREAD pThread)
239{
240 PDRVNAT pThis = PDMINS_2_DATA(pDrvIns, PDRVNAT);
241
242 if (pThread->enmState == PDMTHREADSTATE_INITIALIZING)
243 return VINF_SUCCESS;
244
245 while (pThread->enmState == PDMTHREADSTATE_RUNNING)
246 {
247 RTReqProcess(pThis->pUrgRecvReqQueue, 0);
248 if (ASMAtomicReadU32(&pThis->cUrgPkts) == 0)
249 {
250 int rc = RTSemEventWait(pThis->EventUrgRecv, RT_INDEFINITE_WAIT);
251 AssertRC(rc);
252 }
253 }
254 return VINF_SUCCESS;
255}
256
257static DECLCALLBACK(int) drvNATUrgRecvWakeup(PPDMDRVINS pDrvIns, PPDMTHREAD pThread)
258{
259 PDRVNAT pThis = PDMINS_2_DATA(pDrvIns, PDRVNAT);
260 int rc = RTSemEventSignal(pThis->EventUrgRecv);
261 AssertRC(rc);
262
263 return VINF_SUCCESS;
264}
265
266static DECLCALLBACK(void) drvNATUrgRecvWorker(PDRVNAT pThis, uint8_t *pu8Buf, int cb, struct mbuf *m)
267{
268 int rc = RTCritSectEnter(&pThis->DevAccessLock);
269 AssertRC(rc);
270 rc = pThis->pIAboveNet->pfnWaitReceiveAvail(pThis->pIAboveNet, RT_INDEFINITE_WAIT);
271 if (RT_SUCCESS(rc))
272 {
273 rc = pThis->pIAboveNet->pfnReceive(pThis->pIAboveNet, pu8Buf, cb);
274 AssertRC(rc);
275 }
276 else if ( rc != VERR_TIMEOUT
277 && rc != VERR_INTERRUPTED)
278 {
279 AssertRC(rc);
280 }
281
282 rc = RTCritSectLeave(&pThis->DevAccessLock);
283 AssertRC(rc);
284
285 slirp_ext_m_free(pThis->pNATState, m);
286#ifdef VBOX_WITH_SLIRP_BSD_MBUF
287 RTMemFree(pu8Buf);
288#endif
289 if (ASMAtomicDecU32(&pThis->cUrgPkts) == 0)
290 {
291 drvNATRecvWakeup(pThis->pDrvIns, pThis->pRecvThread);
292 drvNATNotifyNATThread(pThis, "drvNATUrgRecvWorker");
293 }
294}
295
296
297static DECLCALLBACK(void) drvNATRecvWorker(PDRVNAT pThis, uint8_t *pu8Buf, int cb, struct mbuf *m)
298{
299 int rc;
300 STAM_PROFILE_START(&pThis->StatNATRecv, a);
301
302 STAM_PROFILE_START(&pThis->StatNATRecvWait, b);
303
304 while (ASMAtomicReadU32(&pThis->cUrgPkts) != 0)
305 {
306 rc = RTSemEventWait(pThis->EventRecv, RT_INDEFINITE_WAIT);
307 if ( RT_FAILURE(rc)
308 && ( rc == VERR_TIMEOUT
309 || rc == VERR_INTERRUPTED))
310 goto done_unlocked;
311 }
312
313 rc = RTCritSectEnter(&pThis->DevAccessLock);
314 AssertRC(rc);
315
316 rc = pThis->pIAboveNet->pfnWaitReceiveAvail(pThis->pIAboveNet, RT_INDEFINITE_WAIT);
317 if (RT_SUCCESS(rc))
318 {
319 rc = pThis->pIAboveNet->pfnReceive(pThis->pIAboveNet, pu8Buf, cb);
320 AssertRC(rc);
321 }
322 else if ( rc != VERR_TIMEOUT
323 && rc != VERR_INTERRUPTED)
324 {
325 AssertRC(rc);
326 }
327
328 rc = RTCritSectLeave(&pThis->DevAccessLock);
329 AssertRC(rc);
330
331done_unlocked:
332 slirp_ext_m_free(pThis->pNATState, m);
333#ifdef VBOX_WITH_SLIRP_BSD_MBUF
334 RTMemFree(pu8Buf);
335#endif
336 ASMAtomicDecU32(&pThis->cPkts);
337
338 drvNATNotifyNATThread(pThis, "drvNATRecvWorker");
339
340 STAM_PROFILE_STOP(&pThis->StatNATRecvWait, b);
341 STAM_PROFILE_STOP(&pThis->StatNATRecv, a);
342}
343
344/**
345 * Frees a S/G buffer allocated by drvNATNetworkUp_AllocBuf.
346 *
347 * @param pThis Pointer to the NAT instance.
348 * @param pSgBuf The S/G buffer to free.
349 */
350static void drvNATFreeSgBuf(PDRVNAT pThis, PPDMSCATTERGATHER pSgBuf)
351{
352 Assert((pSgBuf->fFlags & PDMSCATTERGATHER_FLAGS_MAGIC_MASK) == PDMSCATTERGATHER_FLAGS_MAGIC);
353 pSgBuf->fFlags = 0;
354 if (pSgBuf->pvAllocator)
355 {
356 Assert(!pSgBuf->pvUser);
357 slirp_ext_m_free(pThis->pNATState, (struct mbuf *)pSgBuf->pvAllocator);
358 pSgBuf->pvAllocator = NULL;
359 }
360 else if (pSgBuf->pvUser)
361 {
362 RTMemFree(pSgBuf->aSegs[0].pvSeg);
363 pSgBuf->aSegs[0].pvSeg = NULL;
364 RTMemFree(pSgBuf->pvUser);
365 pSgBuf->pvUser = NULL;
366 }
367 RTMemFree(pSgBuf);
368}
369
370/**
371 * Worker function for drvNATSend().
372 *
373 * @param pThis Pointer to the NAT instance.
374 * @param pSgBuf The scatter/gather buffer.
375 * @thread NAT
376 */
377static void drvNATSendWorker(PDRVNAT pThis, PPDMSCATTERGATHER pSgBuf)
378{
379 Assert(pThis->enmLinkState == PDMNETWORKLINKSTATE_UP);
380 if (pThis->enmLinkState == PDMNETWORKLINKSTATE_UP)
381 {
382 struct mbuf *m = (struct mbuf *)pSgBuf->pvAllocator;
383 if (m)
384 {
385 /*
386 * A normal frame.
387 */
388 pSgBuf->pvAllocator = NULL;
389 slirp_input(pThis->pNATState, m, pSgBuf->cbUsed);
390 }
391 else
392 {
393 /*
394 * GSO frame, need to segment it.
395 */
396 /** @todo Make the NAT engine grok large frames? Could be more efficient... */
397#if 0 /* this is for testing PDMNetGsoCarveSegmentQD. */
398 uint8_t abHdrScratch[256];
399#endif
400 uint8_t const *pbFrame = (uint8_t const *)pSgBuf->aSegs[0].pvSeg;
401 PCPDMNETWORKGSO pGso = (PCPDMNETWORKGSO)pSgBuf->pvUser;
402 uint32_t const cSegs = PDMNetGsoCalcSegmentCount(pGso, pSgBuf->cbUsed); Assert(cSegs > 1);
403 for (size_t iSeg = 0; iSeg < cSegs; iSeg++)
404 {
405 size_t cbSeg;
406 void *pvSeg;
407 m = slirp_ext_m_get(pThis->pNATState, pGso->cbHdrs + pGso->cbMaxSeg, &pvSeg, &cbSeg);
408 if (!m)
409 break;
410
411#if 1
412 uint32_t cbPayload;
413 uint32_t offPayload = PDMNetGsoCarveSegment(pGso, pbFrame, pSgBuf->cbUsed,
414 iSeg, cSegs, (uint8_t *)pvSeg, &cbPayload);
415 memcpy((uint8_t *)pvSeg + pGso->cbHdrs, pbFrame + offPayload, cbPayload);
416
417 slirp_input(pThis->pNATState, m, cbPayload + pGso->cbHdrs);
418#else
419 uint32_t cbSegFrame;
420 void *pvSegFrame = PDMNetGsoCarveSegmentQD(pGso, (uint8_t *)pbFrame, pSgBuf->cbUsed, abHdrScratch,
421 iSeg, cSegs, &cbSegFrame);
422 memcpy((uint8_t *)pvSeg, pvSegFrame, cbSegFrame);
423
424 slirp_input(pThis->pNATState, m, cbSegFrame);
425#endif
426 }
427 }
428 }
429 drvNATFreeSgBuf(pThis, pSgBuf);
430
431 /** @todo Implement the VERR_TRY_AGAIN drvNATNetworkUp_AllocBuf sematics. */
432}
433
434/**
435 * @interface_method_impl{PDMINETWORKUP,pfnBeginXmit}
436 */
437static DECLCALLBACK(int) drvNATNetworkUp_BeginXmit(PPDMINETWORKUP pInterface, bool fOnWorkerThread)
438{
439 PDRVNAT pThis = RT_FROM_MEMBER(pInterface, DRVNAT, INetworkUp);
440 int rc = RTCritSectTryEnter(&pThis->XmitLock);
441 if (RT_FAILURE(rc))
442 {
443 /** @todo Kick the worker thread when we have one... */
444 rc = VERR_TRY_AGAIN;
445 }
446 return rc;
447}
448
449/**
450 * @interface_method_impl{PDMINETWORKUP,pfnAllocBuf}
451 */
452static DECLCALLBACK(int) drvNATNetworkUp_AllocBuf(PPDMINETWORKUP pInterface, size_t cbMin,
453 PCPDMNETWORKGSO pGso, PPPDMSCATTERGATHER ppSgBuf)
454{
455 PDRVNAT pThis = RT_FROM_MEMBER(pInterface, DRVNAT, INetworkUp);
456 Assert(RTCritSectIsOwner(&pThis->XmitLock));
457
458 /*
459 * Drop the incoming frame if the NAT thread isn't running.
460 */
461 if (pThis->pSlirpThread->enmState != PDMTHREADSTATE_RUNNING)
462 {
463 Log(("drvNATNetowrkUp_AllocBuf: returns VERR_NET_NO_NETWORK\n"));
464 return VERR_NET_NO_NETWORK;
465 }
466
467 /*
468 * Allocate a scatter/gather buffer and an mbuf.
469 */
470 PPDMSCATTERGATHER pSgBuf = (PPDMSCATTERGATHER)RTMemAlloc(sizeof(*pSgBuf));
471 if (!pSgBuf)
472 return VERR_NO_MEMORY;
473 if (!pGso)
474 {
475 pSgBuf->pvUser = NULL;
476 pSgBuf->pvAllocator = slirp_ext_m_get(pThis->pNATState, cbMin,
477 &pSgBuf->aSegs[0].pvSeg, &pSgBuf->aSegs[0].cbSeg);
478 if (!pSgBuf->pvAllocator)
479 {
480 RTMemFree(pSgBuf);
481 /** @todo Implement the VERR_TRY_AGAIN semantics. */
482 return VERR_NO_MEMORY;
483 }
484 }
485 else
486 {
487 pSgBuf->pvUser = RTMemDup(pGso, sizeof(*pGso));
488 pSgBuf->pvAllocator = NULL;
489 pSgBuf->aSegs[0].cbSeg = RT_ALIGN_Z(cbMin, 16);
490 pSgBuf->aSegs[0].pvSeg = RTMemAlloc(pSgBuf->aSegs[0].cbSeg);
491 if (!pSgBuf->pvUser || !pSgBuf->aSegs[0].pvSeg)
492 {
493 RTMemFree(pSgBuf->aSegs[0].pvSeg);
494 RTMemFree(pSgBuf->pvUser);
495 RTMemFree(pSgBuf);
496 /** @todo Implement the VERR_TRY_AGAIN semantics. */
497 return VERR_NO_MEMORY;
498 }
499 }
500
501 /*
502 * Initialize the S/G buffer and return.
503 */
504 pSgBuf->fFlags = PDMSCATTERGATHER_FLAGS_MAGIC | PDMSCATTERGATHER_FLAGS_OWNER_1;
505 pSgBuf->cbUsed = 0;
506 pSgBuf->cbAvailable = pSgBuf->aSegs[0].cbSeg;
507 pSgBuf->cSegs = 1;
508
509#if 0 /* poison */
510 memset(pSgBuf->aSegs[0].pvSeg, 'F', pSgBuf->aSegs[0].cbSeg);
511#endif
512 *ppSgBuf = pSgBuf;
513 return VINF_SUCCESS;
514}
515
516/**
517 * @interface_method_impl{PDMINETWORKUP,pfnFreeBuf}
518 */
519static DECLCALLBACK(int) drvNATNetworkUp_FreeBuf(PPDMINETWORKUP pInterface, PPDMSCATTERGATHER pSgBuf)
520{
521 PDRVNAT pThis = RT_FROM_MEMBER(pInterface, DRVNAT, INetworkUp);
522 Assert(RTCritSectIsOwner(&pThis->XmitLock));
523 drvNATFreeSgBuf(pThis, pSgBuf);
524 return VINF_SUCCESS;
525}
526
527/**
528 * @interface_method_impl{PDMINETWORKUP,pfnSendBuf}
529 */
530static DECLCALLBACK(int) drvNATNetworkUp_SendBuf(PPDMINETWORKUP pInterface, PPDMSCATTERGATHER pSgBuf, bool fOnWorkerThread)
531{
532 PDRVNAT pThis = RT_FROM_MEMBER(pInterface, DRVNAT, INetworkUp);
533 Assert((pSgBuf->fFlags & PDMSCATTERGATHER_FLAGS_OWNER_MASK) == PDMSCATTERGATHER_FLAGS_OWNER_1);
534 Assert(RTCritSectIsOwner(&pThis->XmitLock));
535
536 int rc;
537 if (pThis->pSlirpThread->enmState == PDMTHREADSTATE_RUNNING)
538 {
539#ifdef VBOX_WITH_SLIRP_MT
540 PRTREQQUEUE pQueue = (PRTREQQUEUE)slirp_get_queue(pThis->pNATState);
541#else
542 PRTREQQUEUE pQueue = pThis->pSlirpReqQueue;
543#endif
544 rc = RTReqCallEx(pQueue, NULL /*ppReq*/, 0 /*cMillies*/, RTREQFLAGS_VOID | RTREQFLAGS_NO_WAIT,
545 (PFNRT)drvNATSendWorker, 2, pThis, pSgBuf);
546 if (RT_SUCCESS(rc))
547 {
548 drvNATNotifyNATThread(pThis, "drvNATNetworkUp_SendBuf");
549 return VINF_SUCCESS;
550 }
551
552 rc = VERR_NET_NO_BUFFER_SPACE;
553 }
554 else
555 rc = VERR_NET_DOWN;
556 drvNATFreeSgBuf(pThis, pSgBuf);
557 return rc;
558}
559
560/**
561 * @interface_method_impl{PDMINETWORKUP,pfnEndXmit}
562 */
563static DECLCALLBACK(void) drvNATNetworkUp_EndXmit(PPDMINETWORKUP pInterface)
564{
565 PDRVNAT pThis = RT_FROM_MEMBER(pInterface, DRVNAT, INetworkUp);
566 RTCritSectLeave(&pThis->XmitLock);
567}
568
569/**
570 * Get the NAT thread out of poll/WSAWaitForMultipleEvents
571 */
572static void drvNATNotifyNATThread(PDRVNAT pThis, const char *pszWho)
573{
574 int rc;
575#ifndef RT_OS_WINDOWS
576 /* kick poll() */
577 rc = RTFileWrite(pThis->PipeWrite, "", 1, NULL);
578#else
579 /* kick WSAWaitForMultipleEvents */
580 rc = WSASetEvent(pThis->hWakeupEvent);
581#endif
582 AssertRC(rc);
583}
584
585/**
586 * @interface_method_impl{PDMINETWORKUP,pfnSetPromiscuousMode}
587 */
588static DECLCALLBACK(void) drvNATNetworkUp_SetPromiscuousMode(PPDMINETWORKUP pInterface, bool fPromiscuous)
589{
590 LogFlow(("drvNATNetworkUp_SetPromiscuousMode: fPromiscuous=%d\n", fPromiscuous));
591 /* nothing to do */
592}
593
594/**
595 * Worker function for drvNATNetworkUp_NotifyLinkChanged().
596 * @thread "NAT" thread.
597 */
598static void drvNATNotifyLinkChangedWorker(PDRVNAT pThis, PDMNETWORKLINKSTATE enmLinkState)
599{
600 pThis->enmLinkState = enmLinkState;
601
602 switch (enmLinkState)
603 {
604 case PDMNETWORKLINKSTATE_UP:
605 LogRel(("NAT: link up\n"));
606 slirp_link_up(pThis->pNATState);
607 break;
608
609 case PDMNETWORKLINKSTATE_DOWN:
610 case PDMNETWORKLINKSTATE_DOWN_RESUME:
611 LogRel(("NAT: link down\n"));
612 slirp_link_down(pThis->pNATState);
613 break;
614
615 default:
616 AssertMsgFailed(("drvNATNetworkUp_NotifyLinkChanged: unexpected link state %d\n", enmLinkState));
617 }
618}
619
620/**
621 * Notification on link status changes.
622 *
623 * @param pInterface Pointer to the interface structure containing the called function pointer.
624 * @param enmLinkState The new link state.
625 * @thread EMT
626 */
627static DECLCALLBACK(void) drvNATNetworkUp_NotifyLinkChanged(PPDMINETWORKUP pInterface, PDMNETWORKLINKSTATE enmLinkState)
628{
629 PDRVNAT pThis = RT_FROM_MEMBER(pInterface, DRVNAT, INetworkUp);
630
631 LogFlow(("drvNATNetworkUp_NotifyLinkChanged: enmLinkState=%d\n", enmLinkState));
632
633 /* don't queue new requests when the NAT thread is about to stop */
634 if (pThis->pSlirpThread->enmState != PDMTHREADSTATE_RUNNING)
635 return;
636
637 PRTREQ pReq;
638 int rc = RTReqCallEx(pThis->pSlirpReqQueue, &pReq, 0 /*cMillies*/, RTREQFLAGS_VOID,
639 (PFNRT)drvNATNotifyLinkChangedWorker, 2, pThis, enmLinkState);
640 if (RT_LIKELY(rc == VERR_TIMEOUT))
641 {
642 drvNATNotifyNATThread(pThis, "drvNATNetworkUp_NotifyLinkChanged");
643 rc = RTReqWait(pReq, RT_INDEFINITE_WAIT);
644 AssertRC(rc);
645 }
646 else
647 AssertRC(rc);
648 RTReqFree(pReq);
649}
650
651/**
652 * NAT thread handling the slirp stuff.
653 *
654 * The slirp implementation is single-threaded so we execute this enginre in a
655 * dedicated thread. We take care that this thread does not become the
656 * bottleneck: If the guest wants to send, a request is enqueued into the
657 * pSlirpReqQueue and handled asynchronously by this thread. If this thread
658 * wants to deliver packets to the guest, it enqueues a request into
659 * pRecvReqQueue which is later handled by the Recv thread.
660 */
661static DECLCALLBACK(int) drvNATAsyncIoThread(PPDMDRVINS pDrvIns, PPDMTHREAD pThread)
662{
663 PDRVNAT pThis = PDMINS_2_DATA(pDrvIns, PDRVNAT);
664 int nFDs = -1;
665#ifdef RT_OS_WINDOWS
666 HANDLE *phEvents = slirp_get_events(pThis->pNATState);
667 unsigned int cBreak = 0;
668#else /* RT_OS_WINDOWS */
669 unsigned int cPollNegRet = 0;
670#endif /* !RT_OS_WINDOWS */
671
672 LogFlow(("drvNATAsyncIoThread: pThis=%p\n", pThis));
673
674 if (pThread->enmState == PDMTHREADSTATE_INITIALIZING)
675 return VINF_SUCCESS;
676
677 /*
678 * Polling loop.
679 */
680 while (pThread->enmState == PDMTHREADSTATE_RUNNING)
681 {
682 /*
683 * To prevent concurent execution of sending/receving threads
684 */
685#ifndef RT_OS_WINDOWS
686 nFDs = slirp_get_nsock(pThis->pNATState);
687 /* allocation for all sockets + Management pipe */
688 struct pollfd *polls = (struct pollfd *)RTMemAlloc((1 + nFDs) * sizeof(struct pollfd) + sizeof(uint32_t));
689 if (polls == NULL)
690 return VERR_NO_MEMORY;
691
692 /* don't pass the managemant pipe */
693 slirp_select_fill(pThis->pNATState, &nFDs, &polls[1]);
694
695 polls[0].fd = pThis->PipeRead;
696 /* POLLRDBAND usually doesn't used on Linux but seems used on Solaris */
697 polls[0].events = POLLRDNORM|POLLPRI|POLLRDBAND;
698 polls[0].revents = 0;
699
700 int cChangedFDs = poll(polls, nFDs + 1, slirp_get_timeout_ms(pThis->pNATState));
701 if (cChangedFDs < 0)
702 {
703 if (errno == EINTR)
704 {
705 Log2(("NAT: signal was caught while sleep on poll\n"));
706 /* No error, just process all outstanding requests but don't wait */
707 cChangedFDs = 0;
708 }
709 else if (cPollNegRet++ > 128)
710 {
711 LogRel(("NAT:Poll returns (%s) suppressed %d\n", strerror(errno), cPollNegRet));
712 cPollNegRet = 0;
713 }
714 }
715
716 if (cChangedFDs >= 0)
717 {
718 slirp_select_poll(pThis->pNATState, &polls[1], nFDs);
719 if (polls[0].revents & (POLLRDNORM|POLLPRI|POLLRDBAND))
720 {
721 /* drain the pipe */
722 char ch[1];
723 size_t cbRead;
724 int counter = 0;
725 /*
726 * drvNATSend decoupled so we don't know how many times
727 * device's thread sends before we've entered multiplex,
728 * so to avoid false alarm drain pipe here to the very end
729 *
730 * @todo: Probably we should counter drvNATSend to count how
731 * deep pipe has been filed before drain.
732 *
733 * XXX:Make it reading exactly we need to drain the pipe.
734 */
735 /** @todo use RTPipeCreate + RTPipeRead(,biggerbuffer) here, it's
736 * non-blocking. */
737 RTFileRead(pThis->PipeRead, &ch, 1, &cbRead);
738 }
739 }
740 /* process _all_ outstanding requests but don't wait */
741 RTReqProcess(pThis->pSlirpReqQueue, 0);
742 RTMemFree(polls);
743
744#else /* RT_OS_WINDOWS */
745 nFDs = -1;
746 slirp_select_fill(pThis->pNATState, &nFDs);
747 DWORD dwEvent = WSAWaitForMultipleEvents(nFDs, phEvents, FALSE,
748 slirp_get_timeout_ms(pThis->pNATState),
749 FALSE);
750 if ( (dwEvent < WSA_WAIT_EVENT_0 || dwEvent > WSA_WAIT_EVENT_0 + nFDs - 1)
751 && dwEvent != WSA_WAIT_TIMEOUT)
752 {
753 int error = WSAGetLastError();
754 LogRel(("NAT: WSAWaitForMultipleEvents returned %d (error %d)\n", dwEvent, error));
755 RTAssertPanic();
756 }
757
758 if (dwEvent == WSA_WAIT_TIMEOUT)
759 {
760 /* only check for slow/fast timers */
761 slirp_select_poll(pThis->pNATState, /* fTimeout=*/true, /*fIcmp=*/false);
762 continue;
763 }
764 /* poll the sockets in any case */
765 Log2(("%s: poll\n", __FUNCTION__));
766 slirp_select_poll(pThis->pNATState, /* fTimeout=*/false, /* fIcmp=*/(dwEvent == WSA_WAIT_EVENT_0));
767 /* process _all_ outstanding requests but don't wait */
768 RTReqProcess(pThis->pSlirpReqQueue, 0);
769# ifdef VBOX_NAT_DELAY_HACK
770 if (cBreak++ > 128)
771 {
772 cBreak = 0;
773 RTThreadSleep(2);
774 }
775# endif
776#endif /* RT_OS_WINDOWS */
777 }
778
779 return VINF_SUCCESS;
780}
781
782
783/**
784 * Unblock the send thread so it can respond to a state change.
785 *
786 * @returns VBox status code.
787 * @param pDevIns The pcnet device instance.
788 * @param pThread The send thread.
789 */
790static DECLCALLBACK(int) drvNATAsyncIoWakeup(PPDMDRVINS pDrvIns, PPDMTHREAD pThread)
791{
792 PDRVNAT pThis = PDMINS_2_DATA(pDrvIns, PDRVNAT);
793
794 drvNATNotifyNATThread(pThis, "drvNATAsyncIoWakeup");
795 return VINF_SUCCESS;
796}
797
798#ifdef VBOX_WITH_SLIRP_MT
799
800static DECLCALLBACK(int) drvNATAsyncIoGuest(PPDMDRVINS pDrvIns, PPDMTHREAD pThread)
801{
802 PDRVNAT pThis = PDMINS_2_DATA(pDrvIns, PDRVNAT);
803
804 if (pThread->enmState == PDMTHREADSTATE_INITIALIZING)
805 return VINF_SUCCESS;
806
807 while (pThread->enmState == PDMTHREADSTATE_RUNNING)
808 slirp_process_queue(pThis->pNATState);
809
810 return VINF_SUCCESS;
811}
812
813
814static DECLCALLBACK(int) drvNATAsyncIoGuestWakeup(PPDMDRVINS pDrvIns, PPDMTHREAD pThread)
815{
816 PDRVNAT pThis = PDMINS_2_DATA(pDrvIns, PDRVNAT);
817
818 return VINF_SUCCESS;
819}
820
821#endif /* VBOX_WITH_SLIRP_MT */
822
823/**
824 * Function called by slirp to check if it's possible to feed incoming data to the network port.
825 * @returns 1 if possible.
826 * @returns 0 if not possible.
827 */
828int slirp_can_output(void *pvUser)
829{
830 return 1;
831}
832
833void slirp_push_recv_thread(void *pvUser)
834{
835 PDRVNAT pThis = (PDRVNAT)pvUser;
836 Assert(pThis);
837 drvNATUrgRecvWakeup(pThis->pDrvIns, pThis->pUrgRecvThread);
838}
839
840void slirp_urg_output(void *pvUser, struct mbuf *m, const uint8_t *pu8Buf, int cb)
841{
842 PDRVNAT pThis = (PDRVNAT)pvUser;
843 Assert(pThis);
844
845 PRTREQ pReq = NULL;
846
847 /* don't queue new requests when the NAT thread is about to stop */
848 if (pThis->pSlirpThread->enmState != PDMTHREADSTATE_RUNNING)
849 return;
850
851 ASMAtomicIncU32(&pThis->cUrgPkts);
852 int rc = RTReqCallEx(pThis->pUrgRecvReqQueue, NULL /*ppReq*/, 0 /*cMillies*/, RTREQFLAGS_VOID | RTREQFLAGS_NO_WAIT,
853 (PFNRT)drvNATUrgRecvWorker, 4, pThis, pu8Buf, cb, m);
854 AssertRC(rc);
855 drvNATUrgRecvWakeup(pThis->pDrvIns, pThis->pUrgRecvThread);
856}
857
858/**
859 * Function called by slirp to feed incoming data to the NIC.
860 */
861void slirp_output(void *pvUser, struct mbuf *m, const uint8_t *pu8Buf, int cb)
862{
863 PDRVNAT pThis = (PDRVNAT)pvUser;
864 Assert(pThis);
865
866 LogFlow(("slirp_output BEGIN %x %d\n", pu8Buf, cb));
867 Log2(("slirp_output: pu8Buf=%p cb=%#x (pThis=%p)\n%.*Rhxd\n", pu8Buf, cb, pThis, cb, pu8Buf));
868
869 PRTREQ pReq = NULL;
870
871 /* don't queue new requests when the NAT thread is about to stop */
872 if (pThis->pSlirpThread->enmState != PDMTHREADSTATE_RUNNING)
873 return;
874
875 ASMAtomicIncU32(&pThis->cPkts);
876 int rc = RTReqCallEx(pThis->pRecvReqQueue, NULL /*ppReq*/, 0 /*cMillies*/, RTREQFLAGS_VOID | RTREQFLAGS_NO_WAIT,
877 (PFNRT)drvNATRecvWorker, 4, pThis, pu8Buf, cb, m);
878 AssertRC(rc);
879 drvNATRecvWakeup(pThis->pDrvIns, pThis->pRecvThread);
880 STAM_COUNTER_INC(&pThis->StatQueuePktSent);
881}
882
883
884/**
885 * @interface_method_impl{PDMIBASE,pfnQueryInterface}
886 */
887static DECLCALLBACK(void *) drvNATQueryInterface(PPDMIBASE pInterface, const char *pszIID)
888{
889 PPDMDRVINS pDrvIns = PDMIBASE_2_PDMDRV(pInterface);
890 PDRVNAT pThis = PDMINS_2_DATA(pDrvIns, PDRVNAT);
891
892 PDMIBASE_RETURN_INTERFACE(pszIID, PDMIBASE, &pDrvIns->IBase);
893 PDMIBASE_RETURN_INTERFACE(pszIID, PDMINETWORKUP, &pThis->INetworkUp);
894 return NULL;
895}
896
897
898/**
899 * Get the MAC address into the slirp stack.
900 *
901 * Called by drvNATLoadDone and drvNATPowerOn.
902 */
903static void drvNATSetMac(PDRVNAT pThis)
904{
905 if (pThis->pIAboveConfig)
906 {
907 RTMAC Mac;
908 pThis->pIAboveConfig->pfnGetMac(pThis->pIAboveConfig, &Mac);
909 /* Re-activate the port forwarding. If */
910 slirp_set_ethaddr_and_activate_port_forwarding(pThis->pNATState, Mac.au8, pThis->GuestIP);
911 }
912}
913
914
915/**
916 * After loading we have to pass the MAC address of the ethernet device to the slirp stack.
917 * Otherwise the guest is not reachable until it performs a DHCP request or an ARP request
918 * (usually done during guest boot).
919 */
920static DECLCALLBACK(int) drvNATLoadDone(PPDMDRVINS pDrvIns, PSSMHANDLE pSSMHandle)
921{
922 PDRVNAT pThis = PDMINS_2_DATA(pDrvIns, PDRVNAT);
923 drvNATSetMac(pThis);
924 return VINF_SUCCESS;
925}
926
927
928/**
929 * Some guests might not use DHCP to retrieve an IP but use a static IP.
930 */
931static DECLCALLBACK(void) drvNATPowerOn(PPDMDRVINS pDrvIns)
932{
933 PDRVNAT pThis = PDMINS_2_DATA(pDrvIns, PDRVNAT);
934 drvNATSetMac(pThis);
935}
936
937
938/**
939 * Sets up the redirectors.
940 *
941 * @returns VBox status code.
942 * @param pCfg The configuration handle.
943 */
944static int drvNATConstructRedir(unsigned iInstance, PDRVNAT pThis, PCFGMNODE pCfg, RTIPV4ADDR Network)
945{
946 RTMAC Mac;
947 RT_ZERO(Mac); /* can't get MAC here */
948
949 /*
950 * Enumerate redirections.
951 */
952 for (PCFGMNODE pNode = CFGMR3GetFirstChild(pCfg); pNode; pNode = CFGMR3GetNextChild(pNode))
953 {
954 /*
955 * Validate the port forwarding config.
956 */
957 if (!CFGMR3AreValuesValid(pNode, "Protocol\0UDP\0HostPort\0GuestPort\0GuestIP\0BindIP\0"))
958 return PDMDRV_SET_ERROR(pThis->pDrvIns, VERR_PDM_DRVINS_UNKNOWN_CFG_VALUES, N_("Unknown configuration in port forwarding"));
959
960 /* protocol type */
961 bool fUDP;
962 char szProtocol[32];
963 int rc;
964 GET_STRING(rc, pThis, pNode, "Protocol", szProtocol[0], sizeof(szProtocol));
965 if (rc == VERR_CFGM_VALUE_NOT_FOUND)
966 {
967 fUDP = false;
968 GET_BOOL(rc, pThis, pNode, "UDP", fUDP);
969 }
970 else if (RT_SUCCESS(rc))
971 {
972 if (!RTStrICmp(szProtocol, "TCP"))
973 fUDP = false;
974 else if (!RTStrICmp(szProtocol, "UDP"))
975 fUDP = true;
976 else
977 return PDMDrvHlpVMSetError(pThis->pDrvIns, VERR_INVALID_PARAMETER, RT_SRC_POS,
978 N_("NAT#%d: Invalid configuration value for \"Protocol\": \"%s\""),
979 iInstance, szProtocol);
980 }
981 /* host port */
982 int32_t iHostPort;
983 GET_S32_STRICT(rc, pThis, pNode, "HostPort", iHostPort);
984
985 /* guest port */
986 int32_t iGuestPort;
987 GET_S32_STRICT(rc, pThis, pNode, "GuestPort", iGuestPort);
988
989 /* guest address */
990 struct in_addr GuestIP;
991 /* @todo (vvl) use CTL_* */
992 GETIP_DEF(rc, pThis, pNode, GuestIP, htonl(Network | CTL_GUEST));
993
994 /* Store the guest IP for re-establishing the port-forwarding rules. Note that GuestIP
995 * is not documented. Without */
996 if (pThis->GuestIP == INADDR_ANY)
997 pThis->GuestIP = GuestIP.s_addr;
998
999 /*
1000 * Call slirp about it.
1001 */
1002 struct in_addr BindIP;
1003 GETIP_DEF(rc, pThis, pNode, BindIP, INADDR_ANY);
1004 if (slirp_redir(pThis->pNATState, fUDP, BindIP, iHostPort, GuestIP, iGuestPort, Mac.au8) < 0)
1005 return PDMDrvHlpVMSetError(pThis->pDrvIns, VERR_NAT_REDIR_SETUP, RT_SRC_POS,
1006 N_("NAT#%d: configuration error: failed to set up "
1007 "redirection of %d to %d. Probably a conflict with "
1008 "existing services or other rules"), iInstance, iHostPort,
1009 iGuestPort);
1010 } /* for each redir rule */
1011
1012 return VINF_SUCCESS;
1013}
1014
1015
1016/**
1017 * Destruct a driver instance.
1018 *
1019 * Most VM resources are freed by the VM. This callback is provided so that any non-VM
1020 * resources can be freed correctly.
1021 *
1022 * @param pDrvIns The driver instance data.
1023 */
1024static DECLCALLBACK(void) drvNATDestruct(PPDMDRVINS pDrvIns)
1025{
1026 PDRVNAT pThis = PDMINS_2_DATA(pDrvIns, PDRVNAT);
1027 LogFlow(("drvNATDestruct:\n"));
1028 PDMDRV_CHECK_VERSIONS_RETURN_VOID(pDrvIns);
1029
1030 if (pThis->pNATState)
1031 {
1032 slirp_term(pThis->pNATState);
1033 slirp_deregister_statistics(pThis->pNATState, pDrvIns);
1034#ifdef VBOX_WITH_STATISTICS
1035# define DRV_PROFILE_COUNTER(name, dsc) DEREGISTER_COUNTER(name, pThis)
1036# define DRV_COUNTING_COUNTER(name, dsc) DEREGISTER_COUNTER(name, pThis)
1037# include "counters.h"
1038#endif
1039 pThis->pNATState = NULL;
1040 }
1041
1042 RTReqDestroyQueue(pThis->pSlirpReqQueue);
1043 pThis->pSlirpReqQueue = NULL;
1044
1045 RTReqDestroyQueue(pThis->pUrgRecvReqQueue);
1046 pThis->pUrgRecvReqQueue = NULL;
1047
1048 RTSemEventDestroy(pThis->EventRecv);
1049 pThis->EventRecv = NIL_RTSEMEVENT;
1050
1051 RTSemEventDestroy(pThis->EventUrgRecv);
1052 pThis->EventUrgRecv = NIL_RTSEMEVENT;
1053
1054 if (RTCritSectIsInitialized(&pThis->DevAccessLock))
1055 RTCritSectDelete(&pThis->DevAccessLock);
1056
1057 if (RTCritSectIsInitialized(&pThis->XmitLock))
1058 RTCritSectDelete(&pThis->XmitLock);
1059}
1060
1061
1062/**
1063 * Construct a NAT network transport driver instance.
1064 *
1065 * @copydoc FNPDMDRVCONSTRUCT
1066 */
1067static DECLCALLBACK(int) drvNATConstruct(PPDMDRVINS pDrvIns, PCFGMNODE pCfg, uint32_t fFlags)
1068{
1069 PDRVNAT pThis = PDMINS_2_DATA(pDrvIns, PDRVNAT);
1070 LogFlow(("drvNATConstruct:\n"));
1071 PDMDRV_CHECK_VERSIONS_RETURN(pDrvIns);
1072
1073 /*
1074 * Validate the config.
1075 */
1076 if (!CFGMR3AreValuesValid(pCfg,
1077 "PassDomain\0TFTPPrefix\0BootFile\0Network"
1078 "\0NextServer\0DNSProxy\0BindIP\0UseHostResolver\0"
1079 "SlirpMTU\0AliasMode\0"
1080 "SockRcv\0SockSnd\0TcpRcv\0TcpSnd\0"))
1081 return PDMDRV_SET_ERROR(pDrvIns, VERR_PDM_DRVINS_UNKNOWN_CFG_VALUES,
1082 N_("Unknown NAT configuration option, only supports PassDomain,"
1083 " TFTPPrefix, BootFile and Network"));
1084
1085 /*
1086 * Init the static parts.
1087 */
1088 pThis->pDrvIns = pDrvIns;
1089 pThis->pNATState = NULL;
1090 pThis->pszTFTPPrefix = NULL;
1091 pThis->pszBootFile = NULL;
1092 pThis->pszNextServer = NULL;
1093 pThis->pSlirpReqQueue = NULL;
1094 pThis->pUrgRecvReqQueue = NULL;
1095 pThis->EventRecv = NIL_RTSEMEVENT;
1096 pThis->EventUrgRecv = NIL_RTSEMEVENT;
1097
1098 /* IBase */
1099 pDrvIns->IBase.pfnQueryInterface = drvNATQueryInterface;
1100
1101 /* INetwork */
1102 pThis->INetworkUp.pfnBeginXmit = drvNATNetworkUp_BeginXmit;
1103 pThis->INetworkUp.pfnAllocBuf = drvNATNetworkUp_AllocBuf;
1104 pThis->INetworkUp.pfnFreeBuf = drvNATNetworkUp_FreeBuf;
1105 pThis->INetworkUp.pfnSendBuf = drvNATNetworkUp_SendBuf;
1106 pThis->INetworkUp.pfnEndXmit = drvNATNetworkUp_EndXmit;
1107 pThis->INetworkUp.pfnSetPromiscuousMode = drvNATNetworkUp_SetPromiscuousMode;
1108 pThis->INetworkUp.pfnNotifyLinkChanged = drvNATNetworkUp_NotifyLinkChanged;
1109
1110 /*
1111 * Get the configuration settings.
1112 */
1113 int rc;
1114 bool fPassDomain = true;
1115 GET_BOOL(rc, pThis, pCfg, "PassDomain", fPassDomain);
1116
1117 GET_STRING_ALLOC(rc, pThis, pCfg, "TFTPPrefix", pThis->pszTFTPPrefix);
1118 GET_STRING_ALLOC(rc, pThis, pCfg, "BootFile", pThis->pszBootFile);
1119 GET_STRING_ALLOC(rc, pThis, pCfg, "NextServer", pThis->pszNextServer);
1120
1121 int fDNSProxy = 0;
1122 GET_S32(rc, pThis, pCfg, "DNSProxy", fDNSProxy);
1123 int fUseHostResolver = 0;
1124 GET_S32(rc, pThis, pCfg, "UseHostResolver", fUseHostResolver);
1125#ifdef VBOX_WITH_SLIRP_BSD_MBUF
1126 int MTU = 1500;
1127 GET_S32(rc, pThis, pCfg, "SlirpMTU", MTU);
1128#endif
1129 int i32AliasMode = 0;
1130 int i32MainAliasMode = 0;
1131 GET_S32(rc, pThis, pCfg, "AliasMode", i32MainAliasMode);
1132
1133 i32AliasMode |= (i32MainAliasMode & 0x1 ? 0x1 : 0);
1134 i32AliasMode |= (i32MainAliasMode & 0x2 ? 0x40 : 0);
1135 i32AliasMode |= (i32MainAliasMode & 0x4 ? 0x4 : 0);
1136 /*
1137 * Query the network port interface.
1138 */
1139 pThis->pIAboveNet = PDMIBASE_QUERY_INTERFACE(pDrvIns->pUpBase, PDMINETWORKDOWN);
1140 if (!pThis->pIAboveNet)
1141 return PDMDRV_SET_ERROR(pDrvIns, VERR_PDM_MISSING_INTERFACE_ABOVE,
1142 N_("Configuration error: the above device/driver didn't "
1143 "export the network port interface"));
1144 pThis->pIAboveConfig = PDMIBASE_QUERY_INTERFACE(pDrvIns->pUpBase, PDMINETWORKCONFIG);
1145 if (!pThis->pIAboveConfig)
1146 return PDMDRV_SET_ERROR(pDrvIns, VERR_PDM_MISSING_INTERFACE_ABOVE,
1147 N_("Configuration error: the above device/driver didn't "
1148 "export the network config interface"));
1149
1150 /* Generate a network address for this network card. */
1151 char szNetwork[32]; /* xxx.xxx.xxx.xxx/yy */
1152 GET_STRING(rc, pThis, pCfg, "Network", szNetwork[0], sizeof(szNetwork));
1153 if (rc == VERR_CFGM_VALUE_NOT_FOUND)
1154 return PDMDrvHlpVMSetError(pDrvIns, rc, RT_SRC_POS, N_("NAT%d: Configuration error: "
1155 "missing network"),
1156 pDrvIns->iInstance, szNetwork);
1157
1158 RTIPV4ADDR Network;
1159 RTIPV4ADDR Netmask;
1160 rc = RTCidrStrToIPv4(szNetwork, &Network, &Netmask);
1161 if (RT_FAILURE(rc))
1162 return PDMDrvHlpVMSetError(pDrvIns, rc, RT_SRC_POS, N_("NAT#%d: Configuration error: "
1163 "network '%s' describes not a valid IPv4 network"),
1164 pDrvIns->iInstance, szNetwork);
1165
1166 /*
1167 * Initialize slirp.
1168 */
1169 rc = slirp_init(&pThis->pNATState, RT_H2N_U32(Network), Netmask,
1170 fPassDomain, !!fUseHostResolver, i32AliasMode, pThis);
1171 if (RT_SUCCESS(rc))
1172 {
1173 slirp_set_dhcp_TFTP_prefix(pThis->pNATState, pThis->pszTFTPPrefix);
1174 slirp_set_dhcp_TFTP_bootfile(pThis->pNATState, pThis->pszBootFile);
1175 slirp_set_dhcp_next_server(pThis->pNATState, pThis->pszNextServer);
1176 slirp_set_dhcp_dns_proxy(pThis->pNATState, !!fDNSProxy);
1177#ifdef VBOX_WITH_SLIRP_BSD_MBUF
1178 slirp_set_mtu(pThis->pNATState, MTU);
1179#endif
1180 char *pszBindIP = NULL;
1181 GET_STRING_ALLOC(rc, pThis, pCfg, "BindIP", pszBindIP);
1182 rc = slirp_set_binding_address(pThis->pNATState, pszBindIP);
1183 if (rc != 0)
1184 LogRel(("NAT: value of BindIP has been ignored\n"));
1185
1186 if(pszBindIP != NULL)
1187 MMR3HeapFree(pszBindIP);
1188#define SLIRP_SET_TUNING_VALUE(name, setter) \
1189 do \
1190 { \
1191 int len = 0; \
1192 rc = CFGMR3QueryS32(pCfg, name, &len); \
1193 if (RT_SUCCESS(rc)) \
1194 setter(pThis->pNATState, len); \
1195 } while(0)
1196
1197 SLIRP_SET_TUNING_VALUE("SockRcv", slirp_set_rcvbuf);
1198 SLIRP_SET_TUNING_VALUE("SockSnd", slirp_set_sndbuf);
1199 SLIRP_SET_TUNING_VALUE("TcpRcv", slirp_set_tcp_rcvspace);
1200 SLIRP_SET_TUNING_VALUE("TcpSnd", slirp_set_tcp_sndspace);
1201
1202 slirp_register_statistics(pThis->pNATState, pDrvIns);
1203#ifdef VBOX_WITH_STATISTICS
1204# define DRV_PROFILE_COUNTER(name, dsc) REGISTER_COUNTER(name, pThis, STAMTYPE_PROFILE, STAMUNIT_TICKS_PER_CALL, dsc)
1205# define DRV_COUNTING_COUNTER(name, dsc) REGISTER_COUNTER(name, pThis, STAMTYPE_COUNTER, STAMUNIT_COUNT, dsc)
1206# include "counters.h"
1207#endif
1208
1209 rc = drvNATConstructRedir(pDrvIns->iInstance, pThis, pCfg, Network);
1210 if (RT_SUCCESS(rc))
1211 {
1212 /*
1213 * Register a load done notification to get the MAC address into the slirp
1214 * engine after we loaded a guest state.
1215 */
1216 rc = PDMDrvHlpSSMRegisterLoadDone(pDrvIns, drvNATLoadDone);
1217 AssertRCReturn(rc, rc);
1218
1219 rc = RTReqCreateQueue(&pThis->pSlirpReqQueue);
1220 if (RT_FAILURE(rc))
1221 {
1222 LogRel(("NAT: Can't create request queue\n"));
1223 return rc;
1224 }
1225
1226 rc = RTReqCreateQueue(&pThis->pRecvReqQueue);
1227 if (RT_FAILURE(rc))
1228 {
1229 LogRel(("NAT: Can't create request queue\n"));
1230 return rc;
1231 }
1232
1233 rc = RTReqCreateQueue(&pThis->pUrgRecvReqQueue);
1234 if (RT_FAILURE(rc))
1235 {
1236 LogRel(("NAT: Can't create request queue\n"));
1237 return rc;
1238 }
1239
1240 rc = PDMDrvHlpThreadCreate(pDrvIns, &pThis->pRecvThread, pThis, drvNATRecv,
1241 drvNATRecvWakeup, 128 * _1K, RTTHREADTYPE_IO, "NATRX");
1242 AssertRCReturn(rc, rc);
1243
1244 rc = RTSemEventCreate(&pThis->EventRecv);
1245 AssertRCReturn(rc, rc);
1246
1247 rc = PDMDrvHlpThreadCreate(pDrvIns, &pThis->pUrgRecvThread, pThis, drvNATUrgRecv,
1248 drvNATUrgRecvWakeup, 128 * _1K, RTTHREADTYPE_IO, "NATURGRX");
1249 AssertRCReturn(rc, rc);
1250
1251 rc = RTSemEventCreate(&pThis->EventRecv);
1252 AssertRCReturn(rc, rc);
1253
1254 rc = RTSemEventCreate(&pThis->EventUrgRecv);
1255 AssertRCReturn(rc, rc);
1256
1257 rc = RTCritSectInit(&pThis->DevAccessLock);
1258 AssertRCReturn(rc, rc);
1259
1260 rc = RTCritSectInit(&pThis->XmitLock);
1261 AssertRCReturn(rc, rc);
1262
1263#ifndef RT_OS_WINDOWS
1264 /*
1265 * Create the control pipe.
1266 */
1267 int fds[2];
1268 if (pipe(&fds[0]) != 0) /** @todo RTPipeCreate() or something... */
1269 {
1270 rc = RTErrConvertFromErrno(errno);
1271 AssertRC(rc);
1272 return rc;
1273 }
1274 pThis->PipeRead = fds[0];
1275 pThis->PipeWrite = fds[1];
1276#else
1277 pThis->hWakeupEvent = CreateEvent(NULL, FALSE, FALSE, NULL); /* auto-reset event */
1278 slirp_register_external_event(pThis->pNATState, pThis->hWakeupEvent,
1279 VBOX_WAKEUP_EVENT_INDEX);
1280#endif
1281
1282 rc = PDMDrvHlpThreadCreate(pDrvIns, &pThis->pSlirpThread, pThis, drvNATAsyncIoThread,
1283 drvNATAsyncIoWakeup, 128 * _1K, RTTHREADTYPE_IO, "NAT");
1284 AssertRC(rc);
1285
1286#ifdef VBOX_WITH_SLIRP_MT
1287 rc = PDMDrvHlpThreadCreate(pDrvIns, &pThis->pGuestThread, pThis, drvNATAsyncIoGuest,
1288 drvNATAsyncIoGuestWakeup, 128 * _1K, RTTHREADTYPE_IO, "NATGUEST");
1289 AssertRC(rc);
1290#endif
1291
1292 pThis->enmLinkState = PDMNETWORKLINKSTATE_UP;
1293
1294 /* might return VINF_NAT_DNS */
1295 return rc;
1296 }
1297
1298 /* failure path */
1299 slirp_term(pThis->pNATState);
1300 pThis->pNATState = NULL;
1301 }
1302 else
1303 {
1304 PDMDRV_SET_ERROR(pDrvIns, rc, N_("Unknown error during NAT networking setup: "));
1305 AssertMsgFailed(("Add error message for rc=%d (%Rrc)\n", rc, rc));
1306 }
1307
1308 return rc;
1309}
1310
1311
1312/**
1313 * NAT network transport driver registration record.
1314 */
1315const PDMDRVREG g_DrvNAT =
1316{
1317 /* u32Version */
1318 PDM_DRVREG_VERSION,
1319 /* szName */
1320 "NAT",
1321 /* szRCMod */
1322 "",
1323 /* szR0Mod */
1324 "",
1325 /* pszDescription */
1326 "NAT Network Transport Driver",
1327 /* fFlags */
1328 PDM_DRVREG_FLAGS_HOST_BITS_DEFAULT,
1329 /* fClass. */
1330 PDM_DRVREG_CLASS_NETWORK,
1331 /* cMaxInstances */
1332 16,
1333 /* cbInstance */
1334 sizeof(DRVNAT),
1335 /* pfnConstruct */
1336 drvNATConstruct,
1337 /* pfnDestruct */
1338 drvNATDestruct,
1339 /* pfnRelocate */
1340 NULL,
1341 /* pfnIOCtl */
1342 NULL,
1343 /* pfnPowerOn */
1344 drvNATPowerOn,
1345 /* pfnReset */
1346 NULL,
1347 /* pfnSuspend */
1348 NULL,
1349 /* pfnResume */
1350 NULL,
1351 /* pfnAttach */
1352 NULL,
1353 /* pfnDetach */
1354 NULL,
1355 /* pfnPowerOff */
1356 NULL,
1357 /* pfnSoftReset */
1358 NULL,
1359 /* u32EndVersion */
1360 PDM_DRVREG_VERSION
1361};
1362
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