VirtualBox

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

Last change on this file since 54116 was 54109, checked in by vboxsync, 10 years ago

NAT: Use PDMINETWORKNATCONFIG::pfnNotifyDnsChanged callback if
HAVE_NOTIFICATION_FOR_DNS_UPDATE is enabled - except on OS X, where
for now we still use old OS X specific notifications, so this should
be no-op on OS X. Since HAVE_NOTIFICATION_FOR_DNS_UPDATE is not
enabled for anything but OS X for now, this, for now, is a no-op
elsewhere too. But just enabling HAVE_NOTIFICATION_FOR_DNS_UPDATE in
libslirp.h should now be enough to switch.

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