VirtualBox

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

Last change on this file since 57739 was 57600, checked in by vboxsync, 9 years ago

NAT: don't deadlock if we try to activate a NAT network while the VM is not running

  • Property svn:eol-style set to native
  • Property svn:keywords set to Author Date Id Revision
File size: 62.8 KB
Line 
1/* $Id: DrvNAT.cpp 57600 2015-09-02 16:42:05Z vboxsync $ */
2/** @file
3 * DrvNAT - NAT network transport driver.
4 */
5
6/*
7 * Copyright (C) 2006-2015 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"
26extern "C" {
27#include "slirp/slirp_dns.h"
28}
29#include "slirp/ctl.h"
30
31#include <VBox/vmm/dbgf.h>
32#include <VBox/vmm/pdmdrv.h>
33#include <VBox/vmm/pdmnetifs.h>
34#include <VBox/vmm/pdmnetinline.h>
35
36#include <iprt/assert.h>
37#include <iprt/critsect.h>
38#include <iprt/cidr.h>
39#include <iprt/file.h>
40#include <iprt/mem.h>
41#include <iprt/pipe.h>
42#include <iprt/string.h>
43#include <iprt/stream.h>
44#include <iprt/uuid.h>
45
46#include "VBoxDD.h"
47
48#ifndef RT_OS_WINDOWS
49# include <unistd.h>
50# include <fcntl.h>
51# include <poll.h>
52# include <errno.h>
53#endif
54#ifdef RT_OS_FREEBSD
55# include <netinet/in.h>
56#endif
57#include <iprt/semaphore.h>
58#include <iprt/req.h>
59#ifdef RT_OS_DARWIN
60# include <SystemConfiguration/SystemConfiguration.h>
61# include <CoreFoundation/CoreFoundation.h>
62#endif
63
64#define COUNTERS_INIT
65#include "counters.h"
66
67
68/*********************************************************************************************************************************
69* Defined Constants And Macros *
70*********************************************************************************************************************************/
71
72#define DRVNAT_MAXFRAMESIZE (16 * 1024)
73
74/**
75 * @todo: This is a bad hack to prevent freezing the guest during high network
76 * activity. Windows host only. This needs to be fixed properly.
77 */
78#define VBOX_NAT_DELAY_HACK
79
80#define GET_EXTRADATA(pthis, node, name, rc, type, type_name, var) \
81do { \
82 (rc) = CFGMR3Query ## type((node), name, &(var)); \
83 if (RT_FAILURE((rc)) && (rc) != VERR_CFGM_VALUE_NOT_FOUND) \
84 return PDMDrvHlpVMSetError((pthis)->pDrvIns, (rc), RT_SRC_POS, N_("NAT#%d: configuration query for \"" name "\" " #type_name " failed"), \
85 (pthis)->pDrvIns->iInstance); \
86} while (0)
87
88#define GET_ED_STRICT(pthis, node, name, rc, type, type_name, var) \
89do { \
90 (rc) = CFGMR3Query ## type((node), name, &(var)); \
91 if (RT_FAILURE((rc))) \
92 return PDMDrvHlpVMSetError((pthis)->pDrvIns, (rc), RT_SRC_POS, N_("NAT#%d: configuration query for \"" name "\" " #type_name " failed"), \
93 (pthis)->pDrvIns->iInstance); \
94} while (0)
95
96#define GET_EXTRADATA_N(pthis, node, name, rc, type, type_name, var, var_size) \
97do { \
98 (rc) = CFGMR3Query ## type((node), name, &(var), var_size); \
99 if (RT_FAILURE((rc)) && (rc) != VERR_CFGM_VALUE_NOT_FOUND) \
100 return PDMDrvHlpVMSetError((pthis)->pDrvIns, (rc), RT_SRC_POS, N_("NAT#%d: configuration query for \"" name "\" " #type_name " failed"), \
101 (pthis)->pDrvIns->iInstance); \
102} while (0)
103
104#define GET_BOOL(rc, pthis, node, name, var) \
105 GET_EXTRADATA(pthis, node, name, (rc), Bool, bolean, (var))
106#define GET_STRING(rc, pthis, node, name, var, var_size) \
107 GET_EXTRADATA_N(pthis, node, name, (rc), String, string, (var), (var_size))
108#define GET_STRING_ALLOC(rc, pthis, node, name, var) \
109 GET_EXTRADATA(pthis, node, name, (rc), StringAlloc, string, (var))
110#define GET_S32(rc, pthis, node, name, var) \
111 GET_EXTRADATA(pthis, node, name, (rc), S32, int, (var))
112#define GET_S32_STRICT(rc, pthis, node, name, var) \
113 GET_ED_STRICT(pthis, node, name, (rc), S32, int, (var))
114
115
116
117#define DO_GET_IP(rc, node, instance, status, x) \
118do { \
119 char sz##x[32]; \
120 GET_STRING((rc), (node), (instance), #x, sz ## x[0], sizeof(sz ## x)); \
121 if (rc != VERR_CFGM_VALUE_NOT_FOUND) \
122 (status) = inet_aton(sz ## x, &x); \
123} while (0)
124
125#define GETIP_DEF(rc, node, instance, x, def) \
126do \
127{ \
128 int status = 0; \
129 DO_GET_IP((rc), (node), (instance), status, x); \
130 if (status == 0 || rc == VERR_CFGM_VALUE_NOT_FOUND) \
131 x.s_addr = def; \
132} while (0)
133
134
135/*********************************************************************************************************************************
136* Structures and Typedefs *
137*********************************************************************************************************************************/
138/**
139 * NAT network transport driver instance data.
140 *
141 * @implements PDMINETWORKUP
142 */
143typedef struct DRVNAT
144{
145 /** The network interface. */
146 PDMINETWORKUP INetworkUp;
147 /** The network NAT Engine configureation. */
148 PDMINETWORKNATCONFIG INetworkNATCfg;
149 /** The port we're attached to. */
150 PPDMINETWORKDOWN pIAboveNet;
151 /** The network config of the port we're attached to. */
152 PPDMINETWORKCONFIG pIAboveConfig;
153 /** Pointer to the driver instance. */
154 PPDMDRVINS pDrvIns;
155 /** Link state */
156 PDMNETWORKLINKSTATE enmLinkState;
157 /** NAT state for this instance. */
158 PNATState pNATState;
159 /** TFTP directory prefix. */
160 char *pszTFTPPrefix;
161 /** Boot file name to provide in the DHCP server response. */
162 char *pszBootFile;
163 /** tftp server name to provide in the DHCP server response. */
164 char *pszNextServer;
165 /** Polling thread. */
166 PPDMTHREAD pSlirpThread;
167 /** Queue for NAT-thread-external events. */
168 RTREQQUEUE hSlirpReqQueue;
169 /** The guest IP for port-forwarding. */
170 uint32_t GuestIP;
171 /** Link state set when the VM is suspended. */
172 PDMNETWORKLINKSTATE enmLinkStateWant;
173
174#ifndef RT_OS_WINDOWS
175 /** The write end of the control pipe. */
176 RTPIPE hPipeWrite;
177 /** The read end of the control pipe. */
178 RTPIPE hPipeRead;
179# if HC_ARCH_BITS == 32
180 uint32_t u32Padding;
181# endif
182#else
183 /** for external notification */
184 HANDLE hWakeupEvent;
185#endif
186
187#define DRV_PROFILE_COUNTER(name, dsc) STAMPROFILE Stat ## name
188#define DRV_COUNTING_COUNTER(name, dsc) STAMCOUNTER Stat ## name
189#include "counters.h"
190 /** thread delivering packets for receiving by the guest */
191 PPDMTHREAD pRecvThread;
192 /** thread delivering urg packets for receiving by the guest */
193 PPDMTHREAD pUrgRecvThread;
194 /** event to wakeup the guest receive thread */
195 RTSEMEVENT EventRecv;
196 /** event to wakeup the guest urgent receive thread */
197 RTSEMEVENT EventUrgRecv;
198 /** Receive Req queue (deliver packets to the guest) */
199 RTREQQUEUE hRecvReqQueue;
200 /** Receive Urgent Req queue (deliver packets to the guest). */
201 RTREQQUEUE hUrgRecvReqQueue;
202
203 /** makes access to device func RecvAvail and Recv atomical. */
204 RTCRITSECT DevAccessLock;
205 /** Number of in-flight urgent packets. */
206 volatile uint32_t cUrgPkts;
207 /** Number of in-flight regular packets. */
208 volatile uint32_t cPkts;
209
210 /** Transmit lock taken by BeginXmit and released by EndXmit. */
211 RTCRITSECT XmitLock;
212
213#ifdef RT_OS_DARWIN
214 /* Handle of the DNS watcher runloop source. */
215 CFRunLoopSourceRef hRunLoopSrcDnsWatcher;
216#endif
217} DRVNAT;
218AssertCompileMemberAlignment(DRVNAT, StatNATRecvWakeups, 8);
219/** Pointer to the NAT driver instance data. */
220typedef DRVNAT *PDRVNAT;
221
222
223/*********************************************************************************************************************************
224* Internal Functions *
225*********************************************************************************************************************************/
226static void drvNATNotifyNATThread(PDRVNAT pThis, const char *pszWho);
227DECLINLINE(void) drvNATUpdateDNS(PDRVNAT pThis, bool fFlapLink);
228static DECLCALLBACK(int) drvNATReinitializeHostNameResolving(PDRVNAT pThis);
229
230
231static DECLCALLBACK(int) drvNATRecv(PPDMDRVINS pDrvIns, PPDMTHREAD pThread)
232{
233 PDRVNAT pThis = PDMINS_2_DATA(pDrvIns, PDRVNAT);
234
235 if (pThread->enmState == PDMTHREADSTATE_INITIALIZING)
236 return VINF_SUCCESS;
237
238 while (pThread->enmState == PDMTHREADSTATE_RUNNING)
239 {
240 RTReqQueueProcess(pThis->hRecvReqQueue, 0);
241 if (ASMAtomicReadU32(&pThis->cPkts) == 0)
242 RTSemEventWait(pThis->EventRecv, RT_INDEFINITE_WAIT);
243 }
244 return VINF_SUCCESS;
245}
246
247
248static DECLCALLBACK(int) drvNATRecvWakeup(PPDMDRVINS pDrvIns, PPDMTHREAD pThread)
249{
250 PDRVNAT pThis = PDMINS_2_DATA(pDrvIns, PDRVNAT);
251 int rc;
252 rc = RTSemEventSignal(pThis->EventRecv);
253
254 STAM_COUNTER_INC(&pThis->StatNATRecvWakeups);
255 return VINF_SUCCESS;
256}
257
258static DECLCALLBACK(int) drvNATUrgRecv(PPDMDRVINS pDrvIns, PPDMTHREAD pThread)
259{
260 PDRVNAT pThis = PDMINS_2_DATA(pDrvIns, PDRVNAT);
261
262 if (pThread->enmState == PDMTHREADSTATE_INITIALIZING)
263 return VINF_SUCCESS;
264
265 while (pThread->enmState == PDMTHREADSTATE_RUNNING)
266 {
267 RTReqQueueProcess(pThis->hUrgRecvReqQueue, 0);
268 if (ASMAtomicReadU32(&pThis->cUrgPkts) == 0)
269 {
270 int rc = RTSemEventWait(pThis->EventUrgRecv, RT_INDEFINITE_WAIT);
271 AssertRC(rc);
272 }
273 }
274 return VINF_SUCCESS;
275}
276
277static DECLCALLBACK(int) drvNATUrgRecvWakeup(PPDMDRVINS pDrvIns, PPDMTHREAD pThread)
278{
279 PDRVNAT pThis = PDMINS_2_DATA(pDrvIns, PDRVNAT);
280 int rc = RTSemEventSignal(pThis->EventUrgRecv);
281 AssertRC(rc);
282
283 return VINF_SUCCESS;
284}
285
286static DECLCALLBACK(void) drvNATUrgRecvWorker(PDRVNAT pThis, uint8_t *pu8Buf, int cb, struct mbuf *m)
287{
288 int rc = RTCritSectEnter(&pThis->DevAccessLock);
289 AssertRC(rc);
290 rc = pThis->pIAboveNet->pfnWaitReceiveAvail(pThis->pIAboveNet, RT_INDEFINITE_WAIT);
291 if (RT_SUCCESS(rc))
292 {
293 rc = pThis->pIAboveNet->pfnReceive(pThis->pIAboveNet, pu8Buf, cb);
294 AssertRC(rc);
295 }
296 else if ( rc != VERR_TIMEOUT
297 && rc != VERR_INTERRUPTED)
298 {
299 AssertRC(rc);
300 }
301
302 rc = RTCritSectLeave(&pThis->DevAccessLock);
303 AssertRC(rc);
304
305 slirp_ext_m_free(pThis->pNATState, m, pu8Buf);
306 if (ASMAtomicDecU32(&pThis->cUrgPkts) == 0)
307 {
308 drvNATRecvWakeup(pThis->pDrvIns, pThis->pRecvThread);
309 drvNATNotifyNATThread(pThis, "drvNATUrgRecvWorker");
310 }
311}
312
313
314static DECLCALLBACK(void) drvNATRecvWorker(PDRVNAT pThis, uint8_t *pu8Buf, int cb, struct mbuf *m)
315{
316 int rc;
317 STAM_PROFILE_START(&pThis->StatNATRecv, a);
318
319
320 while (ASMAtomicReadU32(&pThis->cUrgPkts) != 0)
321 {
322 rc = RTSemEventWait(pThis->EventRecv, RT_INDEFINITE_WAIT);
323 if ( RT_FAILURE(rc)
324 && ( rc == VERR_TIMEOUT
325 || rc == VERR_INTERRUPTED))
326 goto done_unlocked;
327 }
328
329 rc = RTCritSectEnter(&pThis->DevAccessLock);
330 AssertRC(rc);
331
332 STAM_PROFILE_START(&pThis->StatNATRecvWait, b);
333 rc = pThis->pIAboveNet->pfnWaitReceiveAvail(pThis->pIAboveNet, RT_INDEFINITE_WAIT);
334 STAM_PROFILE_STOP(&pThis->StatNATRecvWait, b);
335
336 if (RT_SUCCESS(rc))
337 {
338 rc = pThis->pIAboveNet->pfnReceive(pThis->pIAboveNet, pu8Buf, cb);
339 AssertRC(rc);
340 }
341 else if ( rc != VERR_TIMEOUT
342 && rc != VERR_INTERRUPTED)
343 {
344 AssertRC(rc);
345 }
346
347 rc = RTCritSectLeave(&pThis->DevAccessLock);
348 AssertRC(rc);
349
350done_unlocked:
351 slirp_ext_m_free(pThis->pNATState, m, pu8Buf);
352 ASMAtomicDecU32(&pThis->cPkts);
353
354 drvNATNotifyNATThread(pThis, "drvNATRecvWorker");
355
356 STAM_PROFILE_STOP(&pThis->StatNATRecv, a);
357}
358
359/**
360 * Frees a S/G buffer allocated by drvNATNetworkUp_AllocBuf.
361 *
362 * @param pThis Pointer to the NAT instance.
363 * @param pSgBuf The S/G buffer to free.
364 */
365static void drvNATFreeSgBuf(PDRVNAT pThis, PPDMSCATTERGATHER pSgBuf)
366{
367 Assert((pSgBuf->fFlags & PDMSCATTERGATHER_FLAGS_MAGIC_MASK) == PDMSCATTERGATHER_FLAGS_MAGIC);
368 pSgBuf->fFlags = 0;
369 if (pSgBuf->pvAllocator)
370 {
371 Assert(!pSgBuf->pvUser);
372 slirp_ext_m_free(pThis->pNATState, (struct mbuf *)pSgBuf->pvAllocator, NULL);
373 pSgBuf->pvAllocator = NULL;
374 }
375 else if (pSgBuf->pvUser)
376 {
377 RTMemFree(pSgBuf->aSegs[0].pvSeg);
378 pSgBuf->aSegs[0].pvSeg = NULL;
379 RTMemFree(pSgBuf->pvUser);
380 pSgBuf->pvUser = NULL;
381 }
382 RTMemFree(pSgBuf);
383}
384
385/**
386 * Worker function for drvNATSend().
387 *
388 * @param pThis Pointer to the NAT instance.
389 * @param pSgBuf The scatter/gather buffer.
390 * @thread NAT
391 */
392static void drvNATSendWorker(PDRVNAT pThis, PPDMSCATTERGATHER pSgBuf)
393{
394#ifndef DEBUG_andy /* Assertion happens often to me after resuming a VM -- no time to investigate this now. */
395 Assert(pThis->enmLinkState == PDMNETWORKLINKSTATE_UP);
396#endif
397 if (pThis->enmLinkState == PDMNETWORKLINKSTATE_UP)
398 {
399 struct mbuf *m = (struct mbuf *)pSgBuf->pvAllocator;
400 if (m)
401 {
402 /*
403 * A normal frame.
404 */
405 pSgBuf->pvAllocator = NULL;
406 slirp_input(pThis->pNATState, m, pSgBuf->cbUsed);
407 }
408 else
409 {
410 /*
411 * GSO frame, need to segment it.
412 */
413 /** @todo Make the NAT engine grok large frames? Could be more efficient... */
414#if 0 /* this is for testing PDMNetGsoCarveSegmentQD. */
415 uint8_t abHdrScratch[256];
416#endif
417 uint8_t const *pbFrame = (uint8_t const *)pSgBuf->aSegs[0].pvSeg;
418 PCPDMNETWORKGSO pGso = (PCPDMNETWORKGSO)pSgBuf->pvUser;
419 uint32_t const cSegs = PDMNetGsoCalcSegmentCount(pGso, pSgBuf->cbUsed); Assert(cSegs > 1);
420 for (size_t iSeg = 0; iSeg < cSegs; iSeg++)
421 {
422 size_t cbSeg;
423 void *pvSeg;
424 m = slirp_ext_m_get(pThis->pNATState, pGso->cbHdrsTotal + pGso->cbMaxSeg, &pvSeg, &cbSeg);
425 if (!m)
426 break;
427
428#if 1
429 uint32_t cbPayload, cbHdrs;
430 uint32_t offPayload = PDMNetGsoCarveSegment(pGso, pbFrame, pSgBuf->cbUsed,
431 iSeg, cSegs, (uint8_t *)pvSeg, &cbHdrs, &cbPayload);
432 memcpy((uint8_t *)pvSeg + cbHdrs, pbFrame + offPayload, cbPayload);
433
434 slirp_input(pThis->pNATState, m, cbPayload + cbHdrs);
435#else
436 uint32_t cbSegFrame;
437 void *pvSegFrame = PDMNetGsoCarveSegmentQD(pGso, (uint8_t *)pbFrame, pSgBuf->cbUsed, abHdrScratch,
438 iSeg, cSegs, &cbSegFrame);
439 memcpy((uint8_t *)pvSeg, pvSegFrame, cbSegFrame);
440
441 slirp_input(pThis->pNATState, m, cbSegFrame);
442#endif
443 }
444 }
445 }
446 drvNATFreeSgBuf(pThis, pSgBuf);
447
448 /** @todo Implement the VERR_TRY_AGAIN drvNATNetworkUp_AllocBuf semantics. */
449}
450
451/**
452 * @interface_method_impl{PDMINETWORKUP,pfnBeginXmit}
453 */
454static DECLCALLBACK(int) drvNATNetworkUp_BeginXmit(PPDMINETWORKUP pInterface, bool fOnWorkerThread)
455{
456 PDRVNAT pThis = RT_FROM_MEMBER(pInterface, DRVNAT, INetworkUp);
457 int rc = RTCritSectTryEnter(&pThis->XmitLock);
458 if (RT_FAILURE(rc))
459 {
460 /** @todo Kick the worker thread when we have one... */
461 rc = VERR_TRY_AGAIN;
462 }
463 return rc;
464}
465
466/**
467 * @interface_method_impl{PDMINETWORKUP,pfnAllocBuf}
468 */
469static DECLCALLBACK(int) drvNATNetworkUp_AllocBuf(PPDMINETWORKUP pInterface, size_t cbMin,
470 PCPDMNETWORKGSO pGso, PPPDMSCATTERGATHER ppSgBuf)
471{
472 PDRVNAT pThis = RT_FROM_MEMBER(pInterface, DRVNAT, INetworkUp);
473 Assert(RTCritSectIsOwner(&pThis->XmitLock));
474
475 /*
476 * Drop the incoming frame if the NAT thread isn't running.
477 */
478 if (pThis->pSlirpThread->enmState != PDMTHREADSTATE_RUNNING)
479 {
480 Log(("drvNATNetowrkUp_AllocBuf: returns VERR_NET_NO_NETWORK\n"));
481 return VERR_NET_NO_NETWORK;
482 }
483
484 /*
485 * Allocate a scatter/gather buffer and an mbuf.
486 */
487 PPDMSCATTERGATHER pSgBuf = (PPDMSCATTERGATHER)RTMemAlloc(sizeof(*pSgBuf));
488 if (!pSgBuf)
489 return VERR_NO_MEMORY;
490 if (!pGso)
491 {
492 /*
493 * Drop the frame if it is too big.
494 */
495 if (cbMin >= DRVNAT_MAXFRAMESIZE)
496 {
497 Log(("drvNATNetowrkUp_AllocBuf: drops over-sized frame (%u bytes), returns VERR_INVALID_PARAMETER\n",
498 cbMin));
499 return VERR_INVALID_PARAMETER;
500 }
501
502 pSgBuf->pvUser = NULL;
503 pSgBuf->pvAllocator = slirp_ext_m_get(pThis->pNATState, cbMin,
504 &pSgBuf->aSegs[0].pvSeg, &pSgBuf->aSegs[0].cbSeg);
505 if (!pSgBuf->pvAllocator)
506 {
507 RTMemFree(pSgBuf);
508 return VERR_TRY_AGAIN;
509 }
510 }
511 else
512 {
513 /*
514 * Drop the frame if its segment is too big.
515 */
516 if (pGso->cbHdrsTotal + pGso->cbMaxSeg >= DRVNAT_MAXFRAMESIZE)
517 {
518 Log(("drvNATNetowrkUp_AllocBuf: drops over-sized frame (%u bytes), returns VERR_INVALID_PARAMETER\n",
519 pGso->cbHdrsTotal + pGso->cbMaxSeg));
520 return VERR_INVALID_PARAMETER;
521 }
522
523 pSgBuf->pvUser = RTMemDup(pGso, sizeof(*pGso));
524 pSgBuf->pvAllocator = NULL;
525 pSgBuf->aSegs[0].cbSeg = RT_ALIGN_Z(cbMin, 16);
526 pSgBuf->aSegs[0].pvSeg = RTMemAlloc(pSgBuf->aSegs[0].cbSeg);
527 if (!pSgBuf->pvUser || !pSgBuf->aSegs[0].pvSeg)
528 {
529 RTMemFree(pSgBuf->aSegs[0].pvSeg);
530 RTMemFree(pSgBuf->pvUser);
531 RTMemFree(pSgBuf);
532 return VERR_TRY_AGAIN;
533 }
534 }
535
536 /*
537 * Initialize the S/G buffer and return.
538 */
539 pSgBuf->fFlags = PDMSCATTERGATHER_FLAGS_MAGIC | PDMSCATTERGATHER_FLAGS_OWNER_1;
540 pSgBuf->cbUsed = 0;
541 pSgBuf->cbAvailable = pSgBuf->aSegs[0].cbSeg;
542 pSgBuf->cSegs = 1;
543
544#if 0 /* poison */
545 memset(pSgBuf->aSegs[0].pvSeg, 'F', pSgBuf->aSegs[0].cbSeg);
546#endif
547 *ppSgBuf = pSgBuf;
548 return VINF_SUCCESS;
549}
550
551/**
552 * @interface_method_impl{PDMINETWORKUP,pfnFreeBuf}
553 */
554static DECLCALLBACK(int) drvNATNetworkUp_FreeBuf(PPDMINETWORKUP pInterface, PPDMSCATTERGATHER pSgBuf)
555{
556 PDRVNAT pThis = RT_FROM_MEMBER(pInterface, DRVNAT, INetworkUp);
557 Assert(RTCritSectIsOwner(&pThis->XmitLock));
558 drvNATFreeSgBuf(pThis, pSgBuf);
559 return VINF_SUCCESS;
560}
561
562/**
563 * @interface_method_impl{PDMINETWORKUP,pfnSendBuf}
564 */
565static DECLCALLBACK(int) drvNATNetworkUp_SendBuf(PPDMINETWORKUP pInterface, PPDMSCATTERGATHER pSgBuf, bool fOnWorkerThread)
566{
567 PDRVNAT pThis = RT_FROM_MEMBER(pInterface, DRVNAT, INetworkUp);
568 Assert((pSgBuf->fFlags & PDMSCATTERGATHER_FLAGS_OWNER_MASK) == PDMSCATTERGATHER_FLAGS_OWNER_1);
569 Assert(RTCritSectIsOwner(&pThis->XmitLock));
570
571 int rc;
572 if (pThis->pSlirpThread->enmState == PDMTHREADSTATE_RUNNING)
573 {
574 /* Set an FTM checkpoint as this operation changes the state permanently. */
575 PDMDrvHlpFTSetCheckpoint(pThis->pDrvIns, FTMCHECKPOINTTYPE_NETWORK);
576
577 rc = RTReqQueueCallEx(pThis->hSlirpReqQueue, NULL /*ppReq*/, 0 /*cMillies*/,
578 RTREQFLAGS_VOID | RTREQFLAGS_NO_WAIT,
579 (PFNRT)drvNATSendWorker, 2, pThis, pSgBuf);
580 if (RT_SUCCESS(rc))
581 {
582 drvNATNotifyNATThread(pThis, "drvNATNetworkUp_SendBuf");
583 return VINF_SUCCESS;
584 }
585
586 rc = VERR_NET_NO_BUFFER_SPACE;
587 }
588 else
589 rc = VERR_NET_DOWN;
590 drvNATFreeSgBuf(pThis, pSgBuf);
591 return rc;
592}
593
594/**
595 * @interface_method_impl{PDMINETWORKUP,pfnEndXmit}
596 */
597static DECLCALLBACK(void) drvNATNetworkUp_EndXmit(PPDMINETWORKUP pInterface)
598{
599 PDRVNAT pThis = RT_FROM_MEMBER(pInterface, DRVNAT, INetworkUp);
600 RTCritSectLeave(&pThis->XmitLock);
601}
602
603/**
604 * Get the NAT thread out of poll/WSAWaitForMultipleEvents
605 */
606static void drvNATNotifyNATThread(PDRVNAT pThis, const char *pszWho)
607{
608 int rc;
609#ifndef RT_OS_WINDOWS
610 /* kick poll() */
611 size_t cbIgnored;
612 rc = RTPipeWrite(pThis->hPipeWrite, "", 1, &cbIgnored);
613#else
614 /* kick WSAWaitForMultipleEvents */
615 rc = WSASetEvent(pThis->hWakeupEvent);
616#endif
617 AssertRC(rc);
618}
619
620/**
621 * @interface_method_impl{PDMINETWORKUP,pfnSetPromiscuousMode}
622 */
623static DECLCALLBACK(void) drvNATNetworkUp_SetPromiscuousMode(PPDMINETWORKUP pInterface, bool fPromiscuous)
624{
625 LogFlow(("drvNATNetworkUp_SetPromiscuousMode: fPromiscuous=%d\n", fPromiscuous));
626 /* nothing to do */
627}
628
629/**
630 * Worker function for drvNATNetworkUp_NotifyLinkChanged().
631 * @thread "NAT" thread.
632 */
633static void drvNATNotifyLinkChangedWorker(PDRVNAT pThis, PDMNETWORKLINKSTATE enmLinkState)
634{
635 pThis->enmLinkState = pThis->enmLinkStateWant = enmLinkState;
636 switch (enmLinkState)
637 {
638 case PDMNETWORKLINKSTATE_UP:
639 LogRel(("NAT: Link up\n"));
640 slirp_link_up(pThis->pNATState);
641 break;
642
643 case PDMNETWORKLINKSTATE_DOWN:
644 case PDMNETWORKLINKSTATE_DOWN_RESUME:
645 LogRel(("NAT: Link down\n"));
646 slirp_link_down(pThis->pNATState);
647 break;
648
649 default:
650 AssertMsgFailed(("drvNATNetworkUp_NotifyLinkChanged: unexpected link state %d\n", enmLinkState));
651 }
652}
653
654/**
655 * Notification on link status changes.
656 *
657 * @param pInterface Pointer to the interface structure containing the called function pointer.
658 * @param enmLinkState The new link state.
659 * @thread EMT
660 */
661static DECLCALLBACK(void) drvNATNetworkUp_NotifyLinkChanged(PPDMINETWORKUP pInterface, PDMNETWORKLINKSTATE enmLinkState)
662{
663 PDRVNAT pThis = RT_FROM_MEMBER(pInterface, DRVNAT, INetworkUp);
664
665 LogFlow(("drvNATNetworkUp_NotifyLinkChanged: enmLinkState=%d\n", enmLinkState));
666
667 /* Don't queue new requests if the NAT thread is not running (e.g. paused,
668 * stopping), otherwise we would deadlock. Memorize the change. */
669 if (pThis->pSlirpThread->enmState != PDMTHREADSTATE_RUNNING)
670 {
671 pThis->enmLinkStateWant = enmLinkState;
672 return;
673 }
674
675 PRTREQ pReq;
676 int rc = RTReqQueueCallEx(pThis->hSlirpReqQueue, &pReq, 0 /*cMillies*/, RTREQFLAGS_VOID,
677 (PFNRT)drvNATNotifyLinkChangedWorker, 2, pThis, enmLinkState);
678 if (rc == VERR_TIMEOUT)
679 {
680 drvNATNotifyNATThread(pThis, "drvNATNetworkUp_NotifyLinkChanged");
681 rc = RTReqWait(pReq, RT_INDEFINITE_WAIT);
682 AssertRC(rc);
683 }
684 else
685 AssertRC(rc);
686 RTReqRelease(pReq);
687}
688
689static void drvNATNotifyApplyPortForwardCommand(PDRVNAT pThis, bool fRemove,
690 bool fUdp, const char *pHostIp,
691 uint16_t u16HostPort, const char *pGuestIp, uint16_t u16GuestPort)
692{
693 RTMAC Mac;
694 RT_ZERO(Mac); /* can't get MAC here */
695 if (pThis->pIAboveConfig)
696 pThis->pIAboveConfig->pfnGetMac(pThis->pIAboveConfig, &Mac);
697
698 struct in_addr guestIp, hostIp;
699
700 if ( pHostIp == NULL
701 || inet_aton(pHostIp, &hostIp) == 0)
702 hostIp.s_addr = INADDR_ANY;
703
704 if ( pGuestIp == NULL
705 || inet_aton(pGuestIp, &guestIp) == 0)
706 guestIp.s_addr = pThis->GuestIP;
707
708 if (fRemove)
709 slirp_remove_redirect(pThis->pNATState, fUdp, hostIp, u16HostPort, guestIp, u16GuestPort);
710 else
711 slirp_add_redirect(pThis->pNATState, fUdp, hostIp, u16HostPort, guestIp, u16GuestPort, Mac.au8);
712}
713
714static DECLCALLBACK(int) drvNATNetworkNatConfigRedirect(PPDMINETWORKNATCONFIG pInterface, bool fRemove,
715 bool fUdp, const char *pHostIp, uint16_t u16HostPort,
716 const char *pGuestIp, uint16_t u16GuestPort)
717{
718 LogFlowFunc(("fRemove=%d, fUdp=%d, pHostIp=%s, u16HostPort=%u, pGuestIp=%s, u16GuestPort=%u\n",
719 RT_BOOL(fRemove), RT_BOOL(fUdp), pHostIp, u16HostPort, pGuestIp, u16GuestPort));
720 PDRVNAT pThis = RT_FROM_MEMBER(pInterface, DRVNAT, INetworkNATCfg);
721 /* Execute the command directly if the VM is not running. */
722 int rc;
723 if (pThis->pSlirpThread->enmState != PDMTHREADSTATE_RUNNING)
724 {
725 drvNATNotifyApplyPortForwardCommand(pThis, fRemove, fUdp, pHostIp,
726 u16HostPort, pGuestIp,u16GuestPort);
727 rc = VINF_SUCCESS;
728 }
729 else
730 {
731 PRTREQ pReq;
732 rc = RTReqQueueCallEx(pThis->hSlirpReqQueue, &pReq, 0 /*cMillies*/, RTREQFLAGS_VOID,
733 (PFNRT)drvNATNotifyApplyPortForwardCommand, 7, pThis, fRemove,
734 fUdp, pHostIp, u16HostPort, pGuestIp, u16GuestPort);
735 if (rc == VERR_TIMEOUT)
736 {
737 drvNATNotifyNATThread(pThis, "drvNATNetworkNatConfigRedirect");
738 rc = RTReqWait(pReq, RT_INDEFINITE_WAIT);
739 AssertRC(rc);
740 }
741 else
742 AssertRC(rc);
743
744 RTReqRelease(pReq);
745 }
746 return rc;
747}
748
749/**
750 * NAT thread handling the slirp stuff.
751 *
752 * The slirp implementation is single-threaded so we execute this enginre in a
753 * dedicated thread. We take care that this thread does not become the
754 * bottleneck: If the guest wants to send, a request is enqueued into the
755 * hSlirpReqQueue and handled asynchronously by this thread. If this thread
756 * wants to deliver packets to the guest, it enqueues a request into
757 * hRecvReqQueue which is later handled by the Recv thread.
758 */
759static DECLCALLBACK(int) drvNATAsyncIoThread(PPDMDRVINS pDrvIns, PPDMTHREAD pThread)
760{
761 PDRVNAT pThis = PDMINS_2_DATA(pDrvIns, PDRVNAT);
762 int nFDs = -1;
763#ifdef RT_OS_WINDOWS
764 HANDLE *phEvents = slirp_get_events(pThis->pNATState);
765 unsigned int cBreak = 0;
766#else /* RT_OS_WINDOWS */
767 unsigned int cPollNegRet = 0;
768#endif /* !RT_OS_WINDOWS */
769
770 LogFlow(("drvNATAsyncIoThread: pThis=%p\n", pThis));
771
772 if (pThread->enmState == PDMTHREADSTATE_INITIALIZING)
773 return VINF_SUCCESS;
774
775 if (pThis->enmLinkStateWant != pThis->enmLinkState)
776 drvNATNotifyLinkChangedWorker(pThis, pThis->enmLinkStateWant);
777
778 /*
779 * Polling loop.
780 */
781 while (pThread->enmState == PDMTHREADSTATE_RUNNING)
782 {
783 /*
784 * To prevent concurrent execution of sending/receiving threads
785 */
786#ifndef RT_OS_WINDOWS
787 nFDs = slirp_get_nsock(pThis->pNATState);
788 /* allocation for all sockets + Management pipe */
789 struct pollfd *polls = (struct pollfd *)RTMemAlloc((1 + nFDs) * sizeof(struct pollfd) + sizeof(uint32_t));
790 if (polls == NULL)
791 return VERR_NO_MEMORY;
792
793 /* don't pass the management pipe */
794 slirp_select_fill(pThis->pNATState, &nFDs, &polls[1]);
795
796 polls[0].fd = RTPipeToNative(pThis->hPipeRead);
797 /* POLLRDBAND usually doesn't used on Linux but seems used on Solaris */
798 polls[0].events = POLLRDNORM | POLLPRI | POLLRDBAND;
799 polls[0].revents = 0;
800
801 int cChangedFDs = poll(polls, nFDs + 1, slirp_get_timeout_ms(pThis->pNATState));
802 if (cChangedFDs < 0)
803 {
804 if (errno == EINTR)
805 {
806 Log2(("NAT: signal was caught while sleep on poll\n"));
807 /* No error, just process all outstanding requests but don't wait */
808 cChangedFDs = 0;
809 }
810 else if (cPollNegRet++ > 128)
811 {
812 LogRel(("NAT: Poll returns (%s) suppressed %d\n", strerror(errno), cPollNegRet));
813 cPollNegRet = 0;
814 }
815 }
816
817 if (cChangedFDs >= 0)
818 {
819 slirp_select_poll(pThis->pNATState, &polls[1], nFDs);
820 if (polls[0].revents & (POLLRDNORM|POLLPRI|POLLRDBAND))
821 {
822 /* drain the pipe
823 *
824 * Note! drvNATSend decoupled so we don't know how many times
825 * device's thread sends before we've entered multiplex,
826 * so to avoid false alarm drain pipe here to the very end
827 *
828 * @todo: Probably we should counter drvNATSend to count how
829 * deep pipe has been filed before drain.
830 *
831 */
832 /** @todo XXX: Make it reading exactly we need to drain the
833 * pipe.*/
834 char ch;
835 size_t cbRead;
836 RTPipeRead(pThis->hPipeRead, &ch, 1, &cbRead);
837 }
838 }
839 /* process _all_ outstanding requests but don't wait */
840 RTReqQueueProcess(pThis->hSlirpReqQueue, 0);
841 RTMemFree(polls);
842
843#else /* RT_OS_WINDOWS */
844 nFDs = -1;
845 slirp_select_fill(pThis->pNATState, &nFDs);
846 DWORD dwEvent = WSAWaitForMultipleEvents(nFDs, phEvents, FALSE,
847 slirp_get_timeout_ms(pThis->pNATState),
848 /* :fAlertable */ TRUE);
849 if ( (dwEvent < WSA_WAIT_EVENT_0 || dwEvent > WSA_WAIT_EVENT_0 + nFDs - 1)
850 && dwEvent != WSA_WAIT_TIMEOUT && dwEvent != WSA_WAIT_IO_COMPLETION)
851 {
852 int error = WSAGetLastError();
853 LogRel(("NAT: WSAWaitForMultipleEvents returned %d (error %d)\n", dwEvent, error));
854 RTAssertPanic();
855 }
856
857 if (dwEvent == WSA_WAIT_TIMEOUT)
858 {
859 /* only check for slow/fast timers */
860 slirp_select_poll(pThis->pNATState, /* fTimeout=*/true);
861 continue;
862 }
863 /* poll the sockets in any case */
864 Log2(("%s: poll\n", __FUNCTION__));
865 slirp_select_poll(pThis->pNATState, /* fTimeout=*/false);
866 /* process _all_ outstanding requests but don't wait */
867 RTReqQueueProcess(pThis->hSlirpReqQueue, 0);
868# ifdef VBOX_NAT_DELAY_HACK
869 if (cBreak++ > 128)
870 {
871 cBreak = 0;
872 RTThreadSleep(2);
873 }
874# endif
875#endif /* RT_OS_WINDOWS */
876 }
877
878 return VINF_SUCCESS;
879}
880
881
882/**
883 * Unblock the send thread so it can respond to a state change.
884 *
885 * @returns VBox status code.
886 * @param pDevIns The pcnet device instance.
887 * @param pThread The send thread.
888 */
889static DECLCALLBACK(int) drvNATAsyncIoWakeup(PPDMDRVINS pDrvIns, PPDMTHREAD pThread)
890{
891 PDRVNAT pThis = PDMINS_2_DATA(pDrvIns, PDRVNAT);
892
893 drvNATNotifyNATThread(pThis, "drvNATAsyncIoWakeup");
894 return VINF_SUCCESS;
895}
896
897/**
898 * Function called by slirp to check if it's possible to feed incoming data to the network port.
899 * @returns 1 if possible.
900 * @returns 0 if not possible.
901 */
902int slirp_can_output(void *pvUser)
903{
904 return 1;
905}
906
907void slirp_push_recv_thread(void *pvUser)
908{
909 PDRVNAT pThis = (PDRVNAT)pvUser;
910 Assert(pThis);
911 drvNATUrgRecvWakeup(pThis->pDrvIns, pThis->pUrgRecvThread);
912}
913
914void slirp_urg_output(void *pvUser, struct mbuf *m, const uint8_t *pu8Buf, int cb)
915{
916 PDRVNAT pThis = (PDRVNAT)pvUser;
917 Assert(pThis);
918
919 PRTREQ pReq = NULL;
920
921 /* don't queue new requests when the NAT thread is about to stop */
922 if (pThis->pSlirpThread->enmState != PDMTHREADSTATE_RUNNING)
923 return;
924
925 ASMAtomicIncU32(&pThis->cUrgPkts);
926 int rc = RTReqQueueCallEx(pThis->hUrgRecvReqQueue, NULL /*ppReq*/, 0 /*cMillies*/, RTREQFLAGS_VOID | RTREQFLAGS_NO_WAIT,
927 (PFNRT)drvNATUrgRecvWorker, 4, pThis, pu8Buf, cb, m);
928 AssertRC(rc);
929 drvNATUrgRecvWakeup(pThis->pDrvIns, pThis->pUrgRecvThread);
930}
931
932/**
933 * Function called by slirp to wake up device after VERR_TRY_AGAIN
934 */
935void slirp_output_pending(void *pvUser)
936{
937 PDRVNAT pThis = (PDRVNAT)pvUser;
938 Assert(pThis);
939 LogFlowFuncEnter();
940 pThis->pIAboveNet->pfnXmitPending(pThis->pIAboveNet);
941 LogFlowFuncLeave();
942}
943
944/**
945 * Function called by slirp to feed incoming data to the NIC.
946 */
947void slirp_output(void *pvUser, struct mbuf *m, const uint8_t *pu8Buf, int cb)
948{
949 PDRVNAT pThis = (PDRVNAT)pvUser;
950 Assert(pThis);
951
952 LogFlow(("slirp_output BEGIN %p %d\n", pu8Buf, cb));
953 Log6(("slirp_output: pu8Buf=%p cb=%#x (pThis=%p)\n%.*Rhxd\n", pu8Buf, cb, pThis, cb, pu8Buf));
954
955 PRTREQ pReq = NULL;
956
957 /* don't queue new requests when the NAT thread is about to stop */
958 if (pThis->pSlirpThread->enmState != PDMTHREADSTATE_RUNNING)
959 return;
960
961 ASMAtomicIncU32(&pThis->cPkts);
962 int rc = RTReqQueueCallEx(pThis->hRecvReqQueue, NULL /*ppReq*/, 0 /*cMillies*/, RTREQFLAGS_VOID | RTREQFLAGS_NO_WAIT,
963 (PFNRT)drvNATRecvWorker, 4, pThis, pu8Buf, cb, m);
964 AssertRC(rc);
965 drvNATRecvWakeup(pThis->pDrvIns, pThis->pRecvThread);
966 STAM_COUNTER_INC(&pThis->StatQueuePktSent);
967 LogFlowFuncLeave();
968}
969
970
971/**
972 * @interface_method_impl{PDMINETWORKNATCONFIG,pfnNotifyDnsChanged}
973 *
974 * We are notified that host's resolver configuration has changed. In
975 * the current setup we don't get any details and just reread that
976 * information ourselves.
977 */
978static DECLCALLBACK(void) drvNATNotifyDnsChanged(PPDMINETWORKNATCONFIG pInterface)
979{
980 PDRVNAT pThis = RT_FROM_MEMBER(pInterface, DRVNAT, INetworkNATCfg);
981 drvNATUpdateDNS(pThis, /* fFlapLink */ true);
982}
983
984
985#ifdef RT_OS_DARWIN
986/**
987 * Callback for the SystemConfiguration framework to notify us whenever the DNS
988 * server changes.
989 *
990 * @returns nothing.
991 * @param hDynStor The DynamicStore handle.
992 * @param hChangedKey Array of changed keys we watch for.
993 * @param pvUser Opaque user data (NAT driver instance).
994 */
995static DECLCALLBACK(void) drvNatDnsChanged(SCDynamicStoreRef hDynStor, CFArrayRef hChangedKeys, void *pvUser)
996{
997 PDRVNAT pThis = (PDRVNAT)pvUser;
998
999 Log2(("NAT: System configuration has changed\n"));
1000
1001 /* Check if any of parameters we are interested in were actually changed. If the size
1002 * of hChangedKeys is 0, it means that SCDynamicStore has been restarted. */
1003 if (hChangedKeys && CFArrayGetCount(hChangedKeys) > 0)
1004 {
1005 /* Look to the updated parameters in particular. */
1006 CFStringRef pDNSKey = CFSTR("State:/Network/Global/DNS");
1007
1008 if (CFArrayContainsValue(hChangedKeys, CFRangeMake(0, CFArrayGetCount(hChangedKeys)), pDNSKey))
1009 {
1010 LogRel(("NAT: DNS servers changed, triggering reconnect\n"));
1011#if 0
1012 CFDictionaryRef hDnsDict = (CFDictionaryRef)SCDynamicStoreCopyValue(hDynStor, pDNSKey);
1013 if (hDnsDict)
1014 {
1015 CFArrayRef hArrAddresses = (CFArrayRef)CFDictionaryGetValue(hDnsDict, kSCPropNetDNSServerAddresses);
1016 if (hArrAddresses && CFArrayGetCount(hArrAddresses) > 0)
1017 {
1018 /* Dump DNS servers list. */
1019 for (int i = 0; i < CFArrayGetCount(hArrAddresses); i++)
1020 {
1021 CFStringRef pDNSAddrStr = (CFStringRef)CFArrayGetValueAtIndex(hArrAddresses, i);
1022 const char *pszDNSAddr = pDNSAddrStr ? CFStringGetCStringPtr(pDNSAddrStr, CFStringGetSystemEncoding()) : NULL;
1023 LogRel(("NAT: New DNS server#%d: %s\n", i, pszDNSAddr ? pszDNSAddr : "None"));
1024 }
1025 }
1026 else
1027 LogRel(("NAT: DNS server list is empty (1)\n"));
1028
1029 CFRelease(hDnsDict);
1030 }
1031 else
1032 LogRel(("NAT: DNS server list is empty (2)\n"));
1033#endif
1034 drvNATUpdateDNS(pThis, /* fFlapLink */ true);
1035 }
1036 else
1037 Log2(("NAT: No DNS changes detected\n"));
1038 }
1039 else
1040 Log2(("NAT: SCDynamicStore has been restarted\n"));
1041}
1042#endif
1043
1044/**
1045 * @interface_method_impl{PDMIBASE,pfnQueryInterface}
1046 */
1047static DECLCALLBACK(void *) drvNATQueryInterface(PPDMIBASE pInterface, const char *pszIID)
1048{
1049 PPDMDRVINS pDrvIns = PDMIBASE_2_PDMDRV(pInterface);
1050 PDRVNAT pThis = PDMINS_2_DATA(pDrvIns, PDRVNAT);
1051
1052 PDMIBASE_RETURN_INTERFACE(pszIID, PDMIBASE, &pDrvIns->IBase);
1053 PDMIBASE_RETURN_INTERFACE(pszIID, PDMINETWORKUP, &pThis->INetworkUp);
1054 PDMIBASE_RETURN_INTERFACE(pszIID, PDMINETWORKNATCONFIG, &pThis->INetworkNATCfg);
1055 return NULL;
1056}
1057
1058
1059/**
1060 * Get the MAC address into the slirp stack.
1061 *
1062 * Called by drvNATLoadDone and drvNATPowerOn.
1063 */
1064static void drvNATSetMac(PDRVNAT pThis)
1065{
1066 if (pThis->pIAboveConfig)
1067 {
1068 RTMAC Mac;
1069 pThis->pIAboveConfig->pfnGetMac(pThis->pIAboveConfig, &Mac);
1070 /* Re-activate the port forwarding. If */
1071 slirp_set_ethaddr_and_activate_port_forwarding(pThis->pNATState, Mac.au8, pThis->GuestIP);
1072 }
1073}
1074
1075
1076/**
1077 * After loading we have to pass the MAC address of the ethernet device to the slirp stack.
1078 * Otherwise the guest is not reachable until it performs a DHCP request or an ARP request
1079 * (usually done during guest boot).
1080 */
1081static DECLCALLBACK(int) drvNATLoadDone(PPDMDRVINS pDrvIns, PSSMHANDLE pSSMHandle)
1082{
1083 PDRVNAT pThis = PDMINS_2_DATA(pDrvIns, PDRVNAT);
1084 drvNATSetMac(pThis);
1085 return VINF_SUCCESS;
1086}
1087
1088
1089/**
1090 * Some guests might not use DHCP to retrieve an IP but use a static IP.
1091 */
1092static DECLCALLBACK(void) drvNATPowerOn(PPDMDRVINS pDrvIns)
1093{
1094 PDRVNAT pThis = PDMINS_2_DATA(pDrvIns, PDRVNAT);
1095 drvNATSetMac(pThis);
1096}
1097
1098
1099/**
1100 * @interface_method_impl{PDMDEVREG,pfnResume}
1101 */
1102static DECLCALLBACK(void) drvNATResume(PPDMDRVINS pDrvIns)
1103{
1104 PDRVNAT pThis = PDMINS_2_DATA(pDrvIns, PDRVNAT);
1105 VMRESUMEREASON enmReason = PDMDrvHlpVMGetResumeReason(pDrvIns);
1106
1107 switch (enmReason)
1108 {
1109 case VMRESUMEREASON_HOST_RESUME:
1110 bool fFlapLink;
1111#if HAVE_NOTIFICATION_FOR_DNS_UPDATE
1112 /* let event handler do it if necessary */
1113 fFlapLink = false;
1114#else
1115 /* XXX: when in doubt, use brute force */
1116 fFlapLink = true;
1117#endif
1118 drvNATUpdateDNS(pThis, fFlapLink);
1119 return;
1120 default: /* Ignore every other resume reason. */
1121 /* do nothing */
1122 return;
1123 }
1124}
1125
1126
1127static DECLCALLBACK(int) drvNATReinitializeHostNameResolving(PDRVNAT pThis)
1128{
1129 slirpReleaseDnsSettings(pThis->pNATState);
1130 slirpInitializeDnsSettings(pThis->pNATState);
1131 return VINF_SUCCESS;
1132}
1133
1134/**
1135 * This function at this stage could be called from two places, but both from non-NAT thread,
1136 * - drvNATResume (EMT?)
1137 * - drvNatDnsChanged (darwin, GUI or main) "listener"
1138 * When Main's interface IHost will support host network configuration change event on every host,
1139 * we won't call it from drvNATResume, but from listener of Main event in the similar way it done
1140 * for port-forwarding, and it wan't be on GUI/main thread, but on EMT thread only.
1141 *
1142 * Thread here is important, because we need to change DNS server list and domain name (+ perhaps,
1143 * search string) at runtime (VBOX_NAT_ENFORCE_INTERNAL_DNS_UPDATE), we can do it safely on NAT thread,
1144 * so with changing other variables (place where we handle update) the main mechanism of update
1145 * _won't_ be changed, the only thing will change is drop of fFlapLink parameter.
1146 */
1147DECLINLINE(void) drvNATUpdateDNS(PDRVNAT pThis, bool fFlapLink)
1148{
1149 int strategy = slirp_host_network_configuration_change_strategy_selector(pThis->pNATState);
1150 switch (strategy)
1151 {
1152 case VBOX_NAT_DNS_DNSPROXY:
1153 {
1154 /**
1155 * XXX: Here or in _strategy_selector we should deal with network change
1156 * in "network change" scenario domain name change we have to update guest lease
1157 * forcibly.
1158 * Note at that built-in dhcp also updates DNS information on NAT thread.
1159 */
1160 /**
1161 * It's unsafe to to do it directly on non-NAT thread
1162 * so we schedule the worker and kick the NAT thread.
1163 */
1164 int rc = RTReqQueueCallEx(pThis->hSlirpReqQueue, NULL /*ppReq*/, 0 /*cMillies*/,
1165 RTREQFLAGS_VOID | RTREQFLAGS_NO_WAIT,
1166 (PFNRT)drvNATReinitializeHostNameResolving, 1, pThis);
1167 if (RT_SUCCESS(rc))
1168 drvNATNotifyNATThread(pThis, "drvNATUpdateDNS");
1169
1170 return;
1171 }
1172
1173 case VBOX_NAT_DNS_EXTERNAL:
1174 /*
1175 * Host resumed from a suspend and the network might have changed.
1176 * Disconnect the guest from the network temporarily to let it pick up the changes.
1177 */
1178 if (fFlapLink)
1179 pThis->pIAboveConfig->pfnSetLinkState(pThis->pIAboveConfig,
1180 PDMNETWORKLINKSTATE_DOWN_RESUME);
1181 return;
1182
1183 case VBOX_NAT_DNS_HOSTRESOLVER:
1184 default:
1185 return;
1186 }
1187}
1188
1189
1190/**
1191 * Info handler.
1192 */
1193static DECLCALLBACK(void) drvNATInfo(PPDMDRVINS pDrvIns, PCDBGFINFOHLP pHlp, const char *pszArgs)
1194{
1195 PDRVNAT pThis = PDMINS_2_DATA(pDrvIns, PDRVNAT);
1196 slirp_info(pThis->pNATState, pHlp, pszArgs);
1197}
1198
1199#ifdef VBOX_WITH_DNSMAPPING_IN_HOSTRESOLVER
1200static int drvNATConstructDNSMappings(unsigned iInstance, PDRVNAT pThis, PCFGMNODE pMappingsCfg)
1201{
1202 int rc = VINF_SUCCESS;
1203 LogFlowFunc(("ENTER: iInstance:%d\n", iInstance));
1204 for (PCFGMNODE pNode = CFGMR3GetFirstChild(pMappingsCfg); pNode; pNode = CFGMR3GetNextChild(pNode))
1205 {
1206 if (!CFGMR3AreValuesValid(pNode, "HostName\0HostNamePattern\0HostIP\0"))
1207 return PDMDRV_SET_ERROR(pThis->pDrvIns, VERR_PDM_DRVINS_UNKNOWN_CFG_VALUES,
1208 N_("Unknown configuration in dns mapping"));
1209 char szHostNameOrPattern[255];
1210 bool fMatch = false; /* false used for equal matching, and true if wildcard pattern is used. */
1211 RT_ZERO(szHostNameOrPattern);
1212 GET_STRING(rc, pThis, pNode, "HostName", szHostNameOrPattern[0], sizeof(szHostNameOrPattern));
1213 if (rc == VERR_CFGM_VALUE_NOT_FOUND)
1214 {
1215 GET_STRING(rc, pThis, pNode, "HostNamePattern", szHostNameOrPattern[0], sizeof(szHostNameOrPattern));
1216 if (rc == VERR_CFGM_VALUE_NOT_FOUND)
1217 {
1218 char szNodeName[225];
1219 RT_ZERO(szNodeName);
1220 CFGMR3GetName(pNode, szNodeName, sizeof(szNodeName));
1221 LogRel(("NAT: Neither 'HostName' nor 'HostNamePattern' is specified for mapping %s\n", szNodeName));
1222 continue;
1223 }
1224 fMatch = true;
1225 }
1226 struct in_addr HostIP;
1227 GETIP_DEF(rc, pThis, pNode, HostIP, INADDR_ANY);
1228 if (rc == VERR_CFGM_VALUE_NOT_FOUND)
1229 {
1230 LogRel(("NAT: DNS mapping %s is ignored (address not pointed)\n", szHostNameOrPattern));
1231 continue;
1232 }
1233 slirp_add_host_resolver_mapping(pThis->pNATState, fMatch ? NULL : szHostNameOrPattern, fMatch ? szHostNameOrPattern : NULL, HostIP.s_addr);
1234 }
1235 LogFlowFunc(("LEAVE: %Rrc\n", rc));
1236 return rc;
1237}
1238#endif /* !VBOX_WITH_DNSMAPPING_IN_HOSTRESOLVER */
1239
1240
1241/**
1242 * Sets up the redirectors.
1243 *
1244 * @returns VBox status code.
1245 * @param pCfg The configuration handle.
1246 */
1247static int drvNATConstructRedir(unsigned iInstance, PDRVNAT pThis, PCFGMNODE pCfg, PRTNETADDRIPV4 pNetwork)
1248{
1249 RTMAC Mac;
1250 RT_ZERO(Mac); /* can't get MAC here */
1251
1252 /*
1253 * Enumerate redirections.
1254 */
1255 for (PCFGMNODE pNode = CFGMR3GetFirstChild(pCfg); pNode; pNode = CFGMR3GetNextChild(pNode))
1256 {
1257#ifdef VBOX_WITH_DNSMAPPING_IN_HOSTRESOLVER
1258 char szNodeName[32];
1259 CFGMR3GetName(pNode, szNodeName, 32);
1260 if ( !RTStrICmp(szNodeName, "HostResolverMappings")
1261 || !RTStrICmp(szNodeName, "AttachedDriver"))
1262 continue;
1263#endif
1264 /*
1265 * Validate the port forwarding config.
1266 */
1267 if (!CFGMR3AreValuesValid(pNode, "Protocol\0UDP\0HostPort\0GuestPort\0GuestIP\0BindIP\0"))
1268 return PDMDRV_SET_ERROR(pThis->pDrvIns, VERR_PDM_DRVINS_UNKNOWN_CFG_VALUES,
1269 N_("Unknown configuration in port forwarding"));
1270
1271 /* protocol type */
1272 bool fUDP;
1273 char szProtocol[32];
1274 int rc;
1275 GET_STRING(rc, pThis, pNode, "Protocol", szProtocol[0], sizeof(szProtocol));
1276 if (rc == VERR_CFGM_VALUE_NOT_FOUND)
1277 {
1278 fUDP = false;
1279 GET_BOOL(rc, pThis, pNode, "UDP", fUDP);
1280 }
1281 else if (RT_SUCCESS(rc))
1282 {
1283 if (!RTStrICmp(szProtocol, "TCP"))
1284 fUDP = false;
1285 else if (!RTStrICmp(szProtocol, "UDP"))
1286 fUDP = true;
1287 else
1288 return PDMDrvHlpVMSetError(pThis->pDrvIns, VERR_INVALID_PARAMETER, RT_SRC_POS,
1289 N_("NAT#%d: Invalid configuration value for \"Protocol\": \"%s\""),
1290 iInstance, szProtocol);
1291 }
1292 else
1293 return PDMDrvHlpVMSetError(pThis->pDrvIns, rc, RT_SRC_POS,
1294 N_("NAT#%d: configuration query for \"Protocol\" failed"),
1295 iInstance);
1296 /* host port */
1297 int32_t iHostPort;
1298 GET_S32_STRICT(rc, pThis, pNode, "HostPort", iHostPort);
1299
1300 /* guest port */
1301 int32_t iGuestPort;
1302 GET_S32_STRICT(rc, pThis, pNode, "GuestPort", iGuestPort);
1303
1304 /* guest address */
1305 struct in_addr GuestIP;
1306 GETIP_DEF(rc, pThis, pNode, GuestIP, RT_H2N_U32(pNetwork->u | CTL_GUEST));
1307
1308 /* Store the guest IP for re-establishing the port-forwarding rules. Note that GuestIP
1309 * is not documented. Without */
1310 if (pThis->GuestIP == INADDR_ANY)
1311 pThis->GuestIP = GuestIP.s_addr;
1312
1313 /*
1314 * Call slirp about it.
1315 */
1316 struct in_addr BindIP;
1317 GETIP_DEF(rc, pThis, pNode, BindIP, INADDR_ANY);
1318 if (slirp_add_redirect(pThis->pNATState, fUDP, BindIP, iHostPort, GuestIP, iGuestPort, Mac.au8) < 0)
1319 return PDMDrvHlpVMSetError(pThis->pDrvIns, VERR_NAT_REDIR_SETUP, RT_SRC_POS,
1320 N_("NAT#%d: configuration error: failed to set up "
1321 "redirection of %d to %d. Probably a conflict with "
1322 "existing services or other rules"), iInstance, iHostPort,
1323 iGuestPort);
1324 } /* for each redir rule */
1325
1326 return VINF_SUCCESS;
1327}
1328
1329
1330/**
1331 * Destruct a driver instance.
1332 *
1333 * Most VM resources are freed by the VM. This callback is provided so that any non-VM
1334 * resources can be freed correctly.
1335 *
1336 * @param pDrvIns The driver instance data.
1337 */
1338static DECLCALLBACK(void) drvNATDestruct(PPDMDRVINS pDrvIns)
1339{
1340 PDRVNAT pThis = PDMINS_2_DATA(pDrvIns, PDRVNAT);
1341 LogFlow(("drvNATDestruct:\n"));
1342 PDMDRV_CHECK_VERSIONS_RETURN_VOID(pDrvIns);
1343
1344 if (pThis->pNATState)
1345 {
1346 slirp_term(pThis->pNATState);
1347 slirp_deregister_statistics(pThis->pNATState, pDrvIns);
1348#ifdef VBOX_WITH_STATISTICS
1349# define DRV_PROFILE_COUNTER(name, dsc) DEREGISTER_COUNTER(name, pThis)
1350# define DRV_COUNTING_COUNTER(name, dsc) DEREGISTER_COUNTER(name, pThis)
1351# include "counters.h"
1352#endif
1353 pThis->pNATState = NULL;
1354 }
1355
1356 RTReqQueueDestroy(pThis->hSlirpReqQueue);
1357 pThis->hSlirpReqQueue = NIL_RTREQQUEUE;
1358
1359 RTReqQueueDestroy(pThis->hUrgRecvReqQueue);
1360 pThis->hUrgRecvReqQueue = NIL_RTREQQUEUE;
1361
1362 RTSemEventDestroy(pThis->EventRecv);
1363 pThis->EventRecv = NIL_RTSEMEVENT;
1364
1365 RTSemEventDestroy(pThis->EventUrgRecv);
1366 pThis->EventUrgRecv = NIL_RTSEMEVENT;
1367
1368 if (RTCritSectIsInitialized(&pThis->DevAccessLock))
1369 RTCritSectDelete(&pThis->DevAccessLock);
1370
1371 if (RTCritSectIsInitialized(&pThis->XmitLock))
1372 RTCritSectDelete(&pThis->XmitLock);
1373
1374#ifdef RT_OS_DARWIN
1375 /* Cleanup the DNS watcher. */
1376 CFRunLoopRef hRunLoopMain = CFRunLoopGetMain();
1377 CFRetain(hRunLoopMain);
1378 CFRunLoopRemoveSource(hRunLoopMain, pThis->hRunLoopSrcDnsWatcher, kCFRunLoopCommonModes);
1379 CFRelease(hRunLoopMain);
1380 CFRelease(pThis->hRunLoopSrcDnsWatcher);
1381 pThis->hRunLoopSrcDnsWatcher = NULL;
1382#endif
1383}
1384
1385
1386/**
1387 * Construct a NAT network transport driver instance.
1388 *
1389 * @copydoc FNPDMDRVCONSTRUCT
1390 */
1391static DECLCALLBACK(int) drvNATConstruct(PPDMDRVINS pDrvIns, PCFGMNODE pCfg, uint32_t fFlags)
1392{
1393 PDRVNAT pThis = PDMINS_2_DATA(pDrvIns, PDRVNAT);
1394 LogFlow(("drvNATConstruct:\n"));
1395 PDMDRV_CHECK_VERSIONS_RETURN(pDrvIns);
1396
1397 /*
1398 * Init the static parts.
1399 */
1400 pThis->pDrvIns = pDrvIns;
1401 pThis->pNATState = NULL;
1402 pThis->pszTFTPPrefix = NULL;
1403 pThis->pszBootFile = NULL;
1404 pThis->pszNextServer = NULL;
1405 pThis->hSlirpReqQueue = NIL_RTREQQUEUE;
1406 pThis->hUrgRecvReqQueue = NIL_RTREQQUEUE;
1407 pThis->EventRecv = NIL_RTSEMEVENT;
1408 pThis->EventUrgRecv = NIL_RTSEMEVENT;
1409#ifdef RT_OS_DARWIN
1410 pThis->hRunLoopSrcDnsWatcher = NULL;
1411#endif
1412
1413 /* IBase */
1414 pDrvIns->IBase.pfnQueryInterface = drvNATQueryInterface;
1415
1416 /* INetwork */
1417 pThis->INetworkUp.pfnBeginXmit = drvNATNetworkUp_BeginXmit;
1418 pThis->INetworkUp.pfnAllocBuf = drvNATNetworkUp_AllocBuf;
1419 pThis->INetworkUp.pfnFreeBuf = drvNATNetworkUp_FreeBuf;
1420 pThis->INetworkUp.pfnSendBuf = drvNATNetworkUp_SendBuf;
1421 pThis->INetworkUp.pfnEndXmit = drvNATNetworkUp_EndXmit;
1422 pThis->INetworkUp.pfnSetPromiscuousMode = drvNATNetworkUp_SetPromiscuousMode;
1423 pThis->INetworkUp.pfnNotifyLinkChanged = drvNATNetworkUp_NotifyLinkChanged;
1424
1425 /* NAT engine configuration */
1426 pThis->INetworkNATCfg.pfnRedirectRuleCommand = drvNATNetworkNatConfigRedirect;
1427#if HAVE_NOTIFICATION_FOR_DNS_UPDATE && !defined(RT_OS_DARWIN)
1428 /*
1429 * On OS X we stick to the old OS X specific notifications for
1430 * now. Elsewhere use IHostNameResolutionConfigurationChangeEvent
1431 * by enbaling HAVE_NOTIFICATION_FOR_DNS_UPDATE in libslirp.h.
1432 * This code is still in a bit of flux and is implemented and
1433 * enabled in steps to simplify more conservative backporting.
1434 */
1435 pThis->INetworkNATCfg.pfnNotifyDnsChanged = drvNATNotifyDnsChanged;
1436#else
1437 pThis->INetworkNATCfg.pfnNotifyDnsChanged = NULL;
1438#endif
1439
1440 /*
1441 * Validate the config.
1442 */
1443 if (!CFGMR3AreValuesValid(pCfg,
1444 "PassDomain\0TFTPPrefix\0BootFile\0Network"
1445 "\0NextServer\0DNSProxy\0BindIP\0UseHostResolver\0"
1446 "SlirpMTU\0AliasMode\0"
1447 "SockRcv\0SockSnd\0TcpRcv\0TcpSnd\0"
1448 "ICMPCacheLimit\0"
1449 "SoMaxConnection\0"
1450#ifdef VBOX_WITH_DNSMAPPING_IN_HOSTRESOLVER
1451 "HostResolverMappings\0"
1452#endif
1453 ))
1454 return PDMDRV_SET_ERROR(pDrvIns, VERR_PDM_DRVINS_UNKNOWN_CFG_VALUES,
1455 N_("Unknown NAT configuration option, only supports PassDomain,"
1456 " TFTPPrefix, BootFile and Network"));
1457
1458 /*
1459 * Get the configuration settings.
1460 */
1461 int rc;
1462 bool fPassDomain = true;
1463 GET_BOOL(rc, pThis, pCfg, "PassDomain", fPassDomain);
1464
1465 GET_STRING_ALLOC(rc, pThis, pCfg, "TFTPPrefix", pThis->pszTFTPPrefix);
1466 GET_STRING_ALLOC(rc, pThis, pCfg, "BootFile", pThis->pszBootFile);
1467 GET_STRING_ALLOC(rc, pThis, pCfg, "NextServer", pThis->pszNextServer);
1468
1469 int fDNSProxy = 0;
1470 GET_S32(rc, pThis, pCfg, "DNSProxy", fDNSProxy);
1471 int fUseHostResolver = 0;
1472 GET_S32(rc, pThis, pCfg, "UseHostResolver", fUseHostResolver);
1473 int MTU = 1500;
1474 GET_S32(rc, pThis, pCfg, "SlirpMTU", MTU);
1475 int i32AliasMode = 0;
1476 int i32MainAliasMode = 0;
1477 GET_S32(rc, pThis, pCfg, "AliasMode", i32MainAliasMode);
1478 int iIcmpCacheLimit = 100;
1479 GET_S32(rc, pThis, pCfg, "ICMPCacheLimit", iIcmpCacheLimit);
1480
1481 i32AliasMode |= (i32MainAliasMode & 0x1 ? 0x1 : 0);
1482 i32AliasMode |= (i32MainAliasMode & 0x2 ? 0x40 : 0);
1483 i32AliasMode |= (i32MainAliasMode & 0x4 ? 0x4 : 0);
1484 int i32SoMaxConn = 10;
1485 GET_S32(rc, pThis, pCfg, "SoMaxConnection", i32SoMaxConn);
1486 /*
1487 * Query the network port interface.
1488 */
1489 pThis->pIAboveNet = PDMIBASE_QUERY_INTERFACE(pDrvIns->pUpBase, PDMINETWORKDOWN);
1490 if (!pThis->pIAboveNet)
1491 return PDMDRV_SET_ERROR(pDrvIns, VERR_PDM_MISSING_INTERFACE_ABOVE,
1492 N_("Configuration error: the above device/driver didn't "
1493 "export the network port interface"));
1494 pThis->pIAboveConfig = PDMIBASE_QUERY_INTERFACE(pDrvIns->pUpBase, PDMINETWORKCONFIG);
1495 if (!pThis->pIAboveConfig)
1496 return PDMDRV_SET_ERROR(pDrvIns, VERR_PDM_MISSING_INTERFACE_ABOVE,
1497 N_("Configuration error: the above device/driver didn't "
1498 "export the network config interface"));
1499
1500 /* Generate a network address for this network card. */
1501 char szNetwork[32]; /* xxx.xxx.xxx.xxx/yy */
1502 GET_STRING(rc, pThis, pCfg, "Network", szNetwork[0], sizeof(szNetwork));
1503 if (rc == VERR_CFGM_VALUE_NOT_FOUND)
1504 return PDMDrvHlpVMSetError(pDrvIns, rc, RT_SRC_POS, N_("NAT%d: Configuration error: missing network"),
1505 pDrvIns->iInstance);
1506
1507 RTNETADDRIPV4 Network, Netmask;
1508
1509 rc = RTCidrStrToIPv4(szNetwork, &Network, &Netmask);
1510 if (RT_FAILURE(rc))
1511 return PDMDrvHlpVMSetError(pDrvIns, rc, RT_SRC_POS,
1512 N_("NAT#%d: Configuration error: network '%s' describes not a valid IPv4 network"),
1513 pDrvIns->iInstance, szNetwork);
1514
1515 /*
1516 * Initialize slirp.
1517 */
1518 rc = slirp_init(&pThis->pNATState, RT_H2N_U32(Network.u), Netmask.u,
1519 fPassDomain, !!fUseHostResolver, i32AliasMode,
1520 iIcmpCacheLimit, pThis);
1521 if (RT_SUCCESS(rc))
1522 {
1523 slirp_set_dhcp_TFTP_prefix(pThis->pNATState, pThis->pszTFTPPrefix);
1524 slirp_set_dhcp_TFTP_bootfile(pThis->pNATState, pThis->pszBootFile);
1525 slirp_set_dhcp_next_server(pThis->pNATState, pThis->pszNextServer);
1526 slirp_set_dhcp_dns_proxy(pThis->pNATState, !!fDNSProxy);
1527 slirp_set_mtu(pThis->pNATState, MTU);
1528 slirp_set_somaxconn(pThis->pNATState, i32SoMaxConn);
1529 char *pszBindIP = NULL;
1530 GET_STRING_ALLOC(rc, pThis, pCfg, "BindIP", pszBindIP);
1531 rc = slirp_set_binding_address(pThis->pNATState, pszBindIP);
1532 if (rc != 0 && pszBindIP && *pszBindIP)
1533 LogRel(("NAT: Value of BindIP has been ignored\n"));
1534
1535 if(pszBindIP != NULL)
1536 MMR3HeapFree(pszBindIP);
1537#define SLIRP_SET_TUNING_VALUE(name, setter) \
1538 do \
1539 { \
1540 int len = 0; \
1541 rc = CFGMR3QueryS32(pCfg, name, &len); \
1542 if (RT_SUCCESS(rc)) \
1543 setter(pThis->pNATState, len); \
1544 } while(0)
1545
1546 SLIRP_SET_TUNING_VALUE("SockRcv", slirp_set_rcvbuf);
1547 SLIRP_SET_TUNING_VALUE("SockSnd", slirp_set_sndbuf);
1548 SLIRP_SET_TUNING_VALUE("TcpRcv", slirp_set_tcp_rcvspace);
1549 SLIRP_SET_TUNING_VALUE("TcpSnd", slirp_set_tcp_sndspace);
1550
1551 slirp_register_statistics(pThis->pNATState, pDrvIns);
1552#ifdef VBOX_WITH_STATISTICS
1553# define DRV_PROFILE_COUNTER(name, dsc) REGISTER_COUNTER(name, pThis, STAMTYPE_PROFILE, STAMUNIT_TICKS_PER_CALL, dsc)
1554# define DRV_COUNTING_COUNTER(name, dsc) REGISTER_COUNTER(name, pThis, STAMTYPE_COUNTER, STAMUNIT_COUNT, dsc)
1555# include "counters.h"
1556#endif
1557
1558#ifdef VBOX_WITH_DNSMAPPING_IN_HOSTRESOLVER
1559 PCFGMNODE pMappingsCfg = CFGMR3GetChild(pCfg, "HostResolverMappings");
1560
1561 if (pMappingsCfg)
1562 {
1563 rc = drvNATConstructDNSMappings(pDrvIns->iInstance, pThis, pMappingsCfg);
1564 AssertRC(rc);
1565 }
1566#endif
1567 rc = drvNATConstructRedir(pDrvIns->iInstance, pThis, pCfg, &Network);
1568 if (RT_SUCCESS(rc))
1569 {
1570 /*
1571 * Register a load done notification to get the MAC address into the slirp
1572 * engine after we loaded a guest state.
1573 */
1574 rc = PDMDrvHlpSSMRegisterLoadDone(pDrvIns, drvNATLoadDone);
1575 AssertLogRelRCReturn(rc, rc);
1576
1577 rc = RTReqQueueCreate(&pThis->hSlirpReqQueue);
1578 AssertLogRelRCReturn(rc, rc);
1579
1580 rc = RTReqQueueCreate(&pThis->hRecvReqQueue);
1581 AssertLogRelRCReturn(rc, rc);
1582
1583 rc = RTReqQueueCreate(&pThis->hUrgRecvReqQueue);
1584 AssertLogRelRCReturn(rc, rc);
1585
1586 rc = PDMDrvHlpThreadCreate(pDrvIns, &pThis->pRecvThread, pThis, drvNATRecv,
1587 drvNATRecvWakeup, 128 * _1K, RTTHREADTYPE_IO, "NATRX");
1588 AssertRCReturn(rc, rc);
1589
1590 rc = RTSemEventCreate(&pThis->EventRecv);
1591 AssertRCReturn(rc, rc);
1592
1593 rc = PDMDrvHlpThreadCreate(pDrvIns, &pThis->pUrgRecvThread, pThis, drvNATUrgRecv,
1594 drvNATUrgRecvWakeup, 128 * _1K, RTTHREADTYPE_IO, "NATURGRX");
1595 AssertRCReturn(rc, rc);
1596
1597 rc = RTSemEventCreate(&pThis->EventRecv);
1598 AssertRCReturn(rc, rc);
1599
1600 rc = RTSemEventCreate(&pThis->EventUrgRecv);
1601 AssertRCReturn(rc, rc);
1602
1603 rc = RTCritSectInit(&pThis->DevAccessLock);
1604 AssertRCReturn(rc, rc);
1605
1606 rc = RTCritSectInit(&pThis->XmitLock);
1607 AssertRCReturn(rc, rc);
1608
1609 char szTmp[128];
1610 RTStrPrintf(szTmp, sizeof(szTmp), "nat%d", pDrvIns->iInstance);
1611 PDMDrvHlpDBGFInfoRegister(pDrvIns, szTmp, "NAT info.", drvNATInfo);
1612
1613#ifndef RT_OS_WINDOWS
1614 /*
1615 * Create the control pipe.
1616 */
1617 rc = RTPipeCreate(&pThis->hPipeRead, &pThis->hPipeWrite, 0 /*fFlags*/);
1618 AssertRCReturn(rc, rc);
1619#else
1620 pThis->hWakeupEvent = CreateEvent(NULL, FALSE, FALSE, NULL); /* auto-reset event */
1621 slirp_register_external_event(pThis->pNATState, pThis->hWakeupEvent,
1622 VBOX_WAKEUP_EVENT_INDEX);
1623#endif
1624
1625 rc = PDMDrvHlpThreadCreate(pDrvIns, &pThis->pSlirpThread, pThis, drvNATAsyncIoThread,
1626 drvNATAsyncIoWakeup, 128 * _1K, RTTHREADTYPE_IO, "NAT");
1627 AssertRCReturn(rc, rc);
1628
1629 pThis->enmLinkState = pThis->enmLinkStateWant = PDMNETWORKLINKSTATE_UP;
1630
1631#ifdef RT_OS_DARWIN
1632 /* Set up a watcher which notifies us everytime the DNS server changes. */
1633 int rc2 = VINF_SUCCESS;
1634 SCDynamicStoreContext SCDynStorCtx;
1635
1636 SCDynStorCtx.version = 0;
1637 SCDynStorCtx.info = pThis;
1638 SCDynStorCtx.retain = NULL;
1639 SCDynStorCtx.release = NULL;
1640 SCDynStorCtx.copyDescription = NULL;
1641
1642 SCDynamicStoreRef hDynStor = SCDynamicStoreCreate(NULL, CFSTR("org.virtualbox.drvnat"), drvNatDnsChanged, &SCDynStorCtx);
1643 if (hDynStor)
1644 {
1645 CFRunLoopSourceRef hRunLoopSrc = SCDynamicStoreCreateRunLoopSource(NULL, hDynStor, 0);
1646 if (hRunLoopSrc)
1647 {
1648 CFStringRef aWatchKeys[] =
1649 {
1650 CFSTR("State:/Network/Global/DNS")
1651 };
1652 CFArrayRef hArray = CFArrayCreate(NULL, (const void **)aWatchKeys, 1, &kCFTypeArrayCallBacks);
1653
1654 if (hArray)
1655 {
1656 if (SCDynamicStoreSetNotificationKeys(hDynStor, hArray, NULL))
1657 {
1658 CFRunLoopRef hRunLoopMain = CFRunLoopGetMain();
1659 CFRetain(hRunLoopMain);
1660 CFRunLoopAddSource(hRunLoopMain, hRunLoopSrc, kCFRunLoopCommonModes);
1661 CFRelease(hRunLoopMain);
1662 pThis->hRunLoopSrcDnsWatcher = hRunLoopSrc;
1663 }
1664 else
1665 rc2 = VERR_NO_MEMORY;
1666
1667 CFRelease(hArray);
1668 }
1669 else
1670 rc2 = VERR_NO_MEMORY;
1671
1672 if (RT_FAILURE(rc2)) /* Keep the runloop source referenced for destruction. */
1673 CFRelease(hRunLoopSrc);
1674 }
1675 CFRelease(hDynStor);
1676 }
1677 else
1678 rc2 = VERR_NO_MEMORY;
1679
1680 if (RT_FAILURE(rc2))
1681 LogRel(("NAT#%d: Failed to install DNS change notifier. The guest might loose DNS access when switching networks on the host\n",
1682 pDrvIns->iInstance));
1683#endif
1684
1685 /* might return VINF_NAT_DNS */
1686 return rc;
1687 }
1688
1689 /* failure path */
1690 slirp_term(pThis->pNATState);
1691 pThis->pNATState = NULL;
1692 }
1693 else
1694 {
1695 PDMDRV_SET_ERROR(pDrvIns, rc, N_("Unknown error during NAT networking setup: "));
1696 AssertMsgFailed(("Add error message for rc=%d (%Rrc)\n", rc, rc));
1697 }
1698
1699 return rc;
1700}
1701
1702
1703/**
1704 * NAT network transport driver registration record.
1705 */
1706const PDMDRVREG g_DrvNAT =
1707{
1708 /* u32Version */
1709 PDM_DRVREG_VERSION,
1710 /* szName */
1711 "NAT",
1712 /* szRCMod */
1713 "",
1714 /* szR0Mod */
1715 "",
1716 /* pszDescription */
1717 "NAT Network Transport Driver",
1718 /* fFlags */
1719 PDM_DRVREG_FLAGS_HOST_BITS_DEFAULT,
1720 /* fClass. */
1721 PDM_DRVREG_CLASS_NETWORK,
1722 /* cMaxInstances */
1723 ~0U,
1724 /* cbInstance */
1725 sizeof(DRVNAT),
1726 /* pfnConstruct */
1727 drvNATConstruct,
1728 /* pfnDestruct */
1729 drvNATDestruct,
1730 /* pfnRelocate */
1731 NULL,
1732 /* pfnIOCtl */
1733 NULL,
1734 /* pfnPowerOn */
1735 drvNATPowerOn,
1736 /* pfnReset */
1737 NULL,
1738 /* pfnSuspend */
1739 NULL,
1740 /* pfnResume */
1741 drvNATResume,
1742 /* pfnAttach */
1743 NULL,
1744 /* pfnDetach */
1745 NULL,
1746 /* pfnPowerOff */
1747 NULL,
1748 /* pfnSoftReset */
1749 NULL,
1750 /* u32EndVersion */
1751 PDM_DRVREG_VERSION
1752};
1753
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