VirtualBox

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

Last change on this file since 30349 was 30349, checked in by vboxsync, 14 years ago

NAT: allow link down/link up when the VM is suspended

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