VirtualBox

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

Last change on this file since 57444 was 57442, checked in by vboxsync, 9 years ago

DECLCALLBACK and static

  • Property svn:eol-style set to native
  • Property svn:keywords set to Author Date Id Revision
File size: 62.6 KB
Line 
1/* $Id: DrvNAT.cpp 57442 2015-08-18 16:47:42Z 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
578 RTREQQUEUE hQueue = pThis->hSlirpReqQueue;
579
580 rc = RTReqQueueCallEx(hQueue, NULL /*ppReq*/, 0 /*cMillies*/, RTREQFLAGS_VOID | RTREQFLAGS_NO_WAIT,
581 (PFNRT)drvNATSendWorker, 2, pThis, pSgBuf);
582 if (RT_SUCCESS(rc))
583 {
584 drvNATNotifyNATThread(pThis, "drvNATNetworkUp_SendBuf");
585 return VINF_SUCCESS;
586 }
587
588 rc = VERR_NET_NO_BUFFER_SPACE;
589 }
590 else
591 rc = VERR_NET_DOWN;
592 drvNATFreeSgBuf(pThis, pSgBuf);
593 return rc;
594}
595
596/**
597 * @interface_method_impl{PDMINETWORKUP,pfnEndXmit}
598 */
599static DECLCALLBACK(void) drvNATNetworkUp_EndXmit(PPDMINETWORKUP pInterface)
600{
601 PDRVNAT pThis = RT_FROM_MEMBER(pInterface, DRVNAT, INetworkUp);
602 RTCritSectLeave(&pThis->XmitLock);
603}
604
605/**
606 * Get the NAT thread out of poll/WSAWaitForMultipleEvents
607 */
608static void drvNATNotifyNATThread(PDRVNAT pThis, const char *pszWho)
609{
610 int rc;
611#ifndef RT_OS_WINDOWS
612 /* kick poll() */
613 size_t cbIgnored;
614 rc = RTPipeWrite(pThis->hPipeWrite, "", 1, &cbIgnored);
615#else
616 /* kick WSAWaitForMultipleEvents */
617 rc = WSASetEvent(pThis->hWakeupEvent);
618#endif
619 AssertRC(rc);
620}
621
622/**
623 * @interface_method_impl{PDMINETWORKUP,pfnSetPromiscuousMode}
624 */
625static DECLCALLBACK(void) drvNATNetworkUp_SetPromiscuousMode(PPDMINETWORKUP pInterface, bool fPromiscuous)
626{
627 LogFlow(("drvNATNetworkUp_SetPromiscuousMode: fPromiscuous=%d\n", fPromiscuous));
628 /* nothing to do */
629}
630
631/**
632 * Worker function for drvNATNetworkUp_NotifyLinkChanged().
633 * @thread "NAT" thread.
634 */
635static void drvNATNotifyLinkChangedWorker(PDRVNAT pThis, PDMNETWORKLINKSTATE enmLinkState)
636{
637 pThis->enmLinkState = pThis->enmLinkStateWant = enmLinkState;
638 switch (enmLinkState)
639 {
640 case PDMNETWORKLINKSTATE_UP:
641 LogRel(("NAT: Link up\n"));
642 slirp_link_up(pThis->pNATState);
643 break;
644
645 case PDMNETWORKLINKSTATE_DOWN:
646 case PDMNETWORKLINKSTATE_DOWN_RESUME:
647 LogRel(("NAT: Link down\n"));
648 slirp_link_down(pThis->pNATState);
649 break;
650
651 default:
652 AssertMsgFailed(("drvNATNetworkUp_NotifyLinkChanged: unexpected link state %d\n", enmLinkState));
653 }
654}
655
656/**
657 * Notification on link status changes.
658 *
659 * @param pInterface Pointer to the interface structure containing the called function pointer.
660 * @param enmLinkState The new link state.
661 * @thread EMT
662 */
663static DECLCALLBACK(void) drvNATNetworkUp_NotifyLinkChanged(PPDMINETWORKUP pInterface, PDMNETWORKLINKSTATE enmLinkState)
664{
665 PDRVNAT pThis = RT_FROM_MEMBER(pInterface, DRVNAT, INetworkUp);
666
667 LogFlow(("drvNATNetworkUp_NotifyLinkChanged: enmLinkState=%d\n", enmLinkState));
668
669 /* Don't queue new requests when the NAT thread is about to stop.
670 * But the VM could also be paused. So memorize the desired state. */
671 if (pThis->pSlirpThread->enmState != PDMTHREADSTATE_RUNNING)
672 {
673 pThis->enmLinkStateWant = enmLinkState;
674 return;
675 }
676
677 PRTREQ pReq;
678 int rc = RTReqQueueCallEx(pThis->hSlirpReqQueue, &pReq, 0 /*cMillies*/, RTREQFLAGS_VOID,
679 (PFNRT)drvNATNotifyLinkChangedWorker, 2, pThis, enmLinkState);
680 if (RT_LIKELY(rc == VERR_TIMEOUT))
681 {
682 drvNATNotifyNATThread(pThis, "drvNATNetworkUp_NotifyLinkChanged");
683 rc = RTReqWait(pReq, RT_INDEFINITE_WAIT);
684 AssertRC(rc);
685 }
686 else
687 AssertRC(rc);
688 RTReqRelease(pReq);
689}
690
691static void drvNATNotifyApplyPortForwardCommand(PDRVNAT pThis, bool fRemove,
692 bool fUdp, const char *pHostIp,
693 uint16_t u16HostPort, const char *pGuestIp, uint16_t u16GuestPort)
694{
695 RTMAC Mac;
696 RT_ZERO(Mac); /* can't get MAC here */
697 if (pThis->pIAboveConfig)
698 pThis->pIAboveConfig->pfnGetMac(pThis->pIAboveConfig, &Mac);
699
700 struct in_addr guestIp, hostIp;
701
702 if ( pHostIp == NULL
703 || inet_aton(pHostIp, &hostIp) == 0)
704 hostIp.s_addr = INADDR_ANY;
705
706 if ( pGuestIp == NULL
707 || inet_aton(pGuestIp, &guestIp) == 0)
708 guestIp.s_addr = pThis->GuestIP;
709
710 if (fRemove)
711 slirp_remove_redirect(pThis->pNATState, fUdp, hostIp, u16HostPort, guestIp, u16GuestPort);
712 else
713 slirp_add_redirect(pThis->pNATState, fUdp, hostIp, u16HostPort, guestIp, u16GuestPort, Mac.au8);
714}
715
716static DECLCALLBACK(int) drvNATNetworkNatConfig_RedirectRuleCommand(PPDMINETWORKNATCONFIG pInterface, bool fRemove,
717 bool fUdp, const char *pHostIp,
718 uint16_t u16HostPort, const char *pGuestIp, uint16_t u16GuestPort)
719{
720 LogFlowFunc(("fRemove=%d, fUdp=%d, pHostIp=%s, u16HostPort=%u, pGuestIp=%s, u16GuestPort=%u\n",
721 RT_BOOL(fRemove), RT_BOOL(fUdp), pHostIp, u16HostPort, pGuestIp,
722 u16GuestPort));
723 PDRVNAT pThis = RT_FROM_MEMBER(pInterface, DRVNAT, INetworkNATCfg);
724 PRTREQ pReq;
725 int rc = RTReqQueueCallEx(pThis->hSlirpReqQueue, &pReq, 0 /*cMillies*/, RTREQFLAGS_VOID,
726 (PFNRT)drvNATNotifyApplyPortForwardCommand, 7, pThis, fRemove,
727 fUdp, pHostIp, u16HostPort, pGuestIp, u16GuestPort);
728 if (RT_LIKELY(rc == VERR_TIMEOUT))
729 {
730 drvNATNotifyNATThread(pThis, "drvNATNetworkNatConfig_RedirectRuleCommand");
731 rc = RTReqWait(pReq, RT_INDEFINITE_WAIT);
732 AssertRC(rc);
733 }
734 else
735 AssertRC(rc);
736
737 RTReqRelease(pReq);
738 port_forwarding_done:
739 return rc;
740}
741
742/**
743 * NAT thread handling the slirp stuff.
744 *
745 * The slirp implementation is single-threaded so we execute this enginre in a
746 * dedicated thread. We take care that this thread does not become the
747 * bottleneck: If the guest wants to send, a request is enqueued into the
748 * hSlirpReqQueue and handled asynchronously by this thread. If this thread
749 * wants to deliver packets to the guest, it enqueues a request into
750 * hRecvReqQueue which is later handled by the Recv thread.
751 */
752static DECLCALLBACK(int) drvNATAsyncIoThread(PPDMDRVINS pDrvIns, PPDMTHREAD pThread)
753{
754 PDRVNAT pThis = PDMINS_2_DATA(pDrvIns, PDRVNAT);
755 int nFDs = -1;
756#ifdef RT_OS_WINDOWS
757 HANDLE *phEvents = slirp_get_events(pThis->pNATState);
758 unsigned int cBreak = 0;
759#else /* RT_OS_WINDOWS */
760 unsigned int cPollNegRet = 0;
761#endif /* !RT_OS_WINDOWS */
762
763 LogFlow(("drvNATAsyncIoThread: pThis=%p\n", pThis));
764
765 if (pThread->enmState == PDMTHREADSTATE_INITIALIZING)
766 return VINF_SUCCESS;
767
768 if (pThis->enmLinkStateWant != pThis->enmLinkState)
769 drvNATNotifyLinkChangedWorker(pThis, pThis->enmLinkStateWant);
770
771 /*
772 * Polling loop.
773 */
774 while (pThread->enmState == PDMTHREADSTATE_RUNNING)
775 {
776 /*
777 * To prevent concurrent execution of sending/receiving threads
778 */
779#ifndef RT_OS_WINDOWS
780 nFDs = slirp_get_nsock(pThis->pNATState);
781 /* allocation for all sockets + Management pipe */
782 struct pollfd *polls = (struct pollfd *)RTMemAlloc((1 + nFDs) * sizeof(struct pollfd) + sizeof(uint32_t));
783 if (polls == NULL)
784 return VERR_NO_MEMORY;
785
786 /* don't pass the management pipe */
787 slirp_select_fill(pThis->pNATState, &nFDs, &polls[1]);
788
789 polls[0].fd = RTPipeToNative(pThis->hPipeRead);
790 /* POLLRDBAND usually doesn't used on Linux but seems used on Solaris */
791 polls[0].events = POLLRDNORM | POLLPRI | POLLRDBAND;
792 polls[0].revents = 0;
793
794 int cChangedFDs = poll(polls, nFDs + 1, slirp_get_timeout_ms(pThis->pNATState));
795 if (cChangedFDs < 0)
796 {
797 if (errno == EINTR)
798 {
799 Log2(("NAT: signal was caught while sleep on poll\n"));
800 /* No error, just process all outstanding requests but don't wait */
801 cChangedFDs = 0;
802 }
803 else if (cPollNegRet++ > 128)
804 {
805 LogRel(("NAT: Poll returns (%s) suppressed %d\n", strerror(errno), cPollNegRet));
806 cPollNegRet = 0;
807 }
808 }
809
810 if (cChangedFDs >= 0)
811 {
812 slirp_select_poll(pThis->pNATState, &polls[1], nFDs);
813 if (polls[0].revents & (POLLRDNORM|POLLPRI|POLLRDBAND))
814 {
815 /* drain the pipe
816 *
817 * Note! drvNATSend decoupled so we don't know how many times
818 * device's thread sends before we've entered multiplex,
819 * so to avoid false alarm drain pipe here to the very end
820 *
821 * @todo: Probably we should counter drvNATSend to count how
822 * deep pipe has been filed before drain.
823 *
824 */
825 /** @todo XXX: Make it reading exactly we need to drain the
826 * pipe.*/
827 char ch;
828 size_t cbRead;
829 RTPipeRead(pThis->hPipeRead, &ch, 1, &cbRead);
830 }
831 }
832 /* process _all_ outstanding requests but don't wait */
833 RTReqQueueProcess(pThis->hSlirpReqQueue, 0);
834 RTMemFree(polls);
835
836#else /* RT_OS_WINDOWS */
837 nFDs = -1;
838 slirp_select_fill(pThis->pNATState, &nFDs);
839 DWORD dwEvent = WSAWaitForMultipleEvents(nFDs, phEvents, FALSE,
840 slirp_get_timeout_ms(pThis->pNATState),
841 /* :fAlertable */ TRUE);
842 if ( (dwEvent < WSA_WAIT_EVENT_0 || dwEvent > WSA_WAIT_EVENT_0 + nFDs - 1)
843 && dwEvent != WSA_WAIT_TIMEOUT && dwEvent != WSA_WAIT_IO_COMPLETION)
844 {
845 int error = WSAGetLastError();
846 LogRel(("NAT: WSAWaitForMultipleEvents returned %d (error %d)\n", dwEvent, error));
847 RTAssertPanic();
848 }
849
850 if (dwEvent == WSA_WAIT_TIMEOUT)
851 {
852 /* only check for slow/fast timers */
853 slirp_select_poll(pThis->pNATState, /* fTimeout=*/true);
854 continue;
855 }
856 /* poll the sockets in any case */
857 Log2(("%s: poll\n", __FUNCTION__));
858 slirp_select_poll(pThis->pNATState, /* fTimeout=*/false);
859 /* process _all_ outstanding requests but don't wait */
860 RTReqQueueProcess(pThis->hSlirpReqQueue, 0);
861# ifdef VBOX_NAT_DELAY_HACK
862 if (cBreak++ > 128)
863 {
864 cBreak = 0;
865 RTThreadSleep(2);
866 }
867# endif
868#endif /* RT_OS_WINDOWS */
869 }
870
871 return VINF_SUCCESS;
872}
873
874
875/**
876 * Unblock the send thread so it can respond to a state change.
877 *
878 * @returns VBox status code.
879 * @param pDevIns The pcnet device instance.
880 * @param pThread The send thread.
881 */
882static DECLCALLBACK(int) drvNATAsyncIoWakeup(PPDMDRVINS pDrvIns, PPDMTHREAD pThread)
883{
884 PDRVNAT pThis = PDMINS_2_DATA(pDrvIns, PDRVNAT);
885
886 drvNATNotifyNATThread(pThis, "drvNATAsyncIoWakeup");
887 return VINF_SUCCESS;
888}
889
890/**
891 * Function called by slirp to check if it's possible to feed incoming data to the network port.
892 * @returns 1 if possible.
893 * @returns 0 if not possible.
894 */
895int slirp_can_output(void *pvUser)
896{
897 return 1;
898}
899
900void slirp_push_recv_thread(void *pvUser)
901{
902 PDRVNAT pThis = (PDRVNAT)pvUser;
903 Assert(pThis);
904 drvNATUrgRecvWakeup(pThis->pDrvIns, pThis->pUrgRecvThread);
905}
906
907void slirp_urg_output(void *pvUser, struct mbuf *m, const uint8_t *pu8Buf, int cb)
908{
909 PDRVNAT pThis = (PDRVNAT)pvUser;
910 Assert(pThis);
911
912 PRTREQ pReq = NULL;
913
914 /* don't queue new requests when the NAT thread is about to stop */
915 if (pThis->pSlirpThread->enmState != PDMTHREADSTATE_RUNNING)
916 return;
917
918 ASMAtomicIncU32(&pThis->cUrgPkts);
919 int rc = RTReqQueueCallEx(pThis->hUrgRecvReqQueue, NULL /*ppReq*/, 0 /*cMillies*/, RTREQFLAGS_VOID | RTREQFLAGS_NO_WAIT,
920 (PFNRT)drvNATUrgRecvWorker, 4, pThis, pu8Buf, cb, m);
921 AssertRC(rc);
922 drvNATUrgRecvWakeup(pThis->pDrvIns, pThis->pUrgRecvThread);
923}
924
925/**
926 * Function called by slirp to wake up device after VERR_TRY_AGAIN
927 */
928void slirp_output_pending(void *pvUser)
929{
930 PDRVNAT pThis = (PDRVNAT)pvUser;
931 Assert(pThis);
932 LogFlowFuncEnter();
933 pThis->pIAboveNet->pfnXmitPending(pThis->pIAboveNet);
934 LogFlowFuncLeave();
935}
936
937/**
938 * Function called by slirp to feed incoming data to the NIC.
939 */
940void slirp_output(void *pvUser, struct mbuf *m, const uint8_t *pu8Buf, int cb)
941{
942 PDRVNAT pThis = (PDRVNAT)pvUser;
943 Assert(pThis);
944
945 LogFlow(("slirp_output BEGIN %p %d\n", pu8Buf, cb));
946 Log6(("slirp_output: pu8Buf=%p cb=%#x (pThis=%p)\n%.*Rhxd\n", pu8Buf, cb, pThis, cb, pu8Buf));
947
948 PRTREQ pReq = NULL;
949
950 /* don't queue new requests when the NAT thread is about to stop */
951 if (pThis->pSlirpThread->enmState != PDMTHREADSTATE_RUNNING)
952 return;
953
954 ASMAtomicIncU32(&pThis->cPkts);
955 int rc = RTReqQueueCallEx(pThis->hRecvReqQueue, NULL /*ppReq*/, 0 /*cMillies*/, RTREQFLAGS_VOID | RTREQFLAGS_NO_WAIT,
956 (PFNRT)drvNATRecvWorker, 4, pThis, pu8Buf, cb, m);
957 AssertRC(rc);
958 drvNATRecvWakeup(pThis->pDrvIns, pThis->pRecvThread);
959 STAM_COUNTER_INC(&pThis->StatQueuePktSent);
960 LogFlowFuncLeave();
961}
962
963
964/**
965 * @interface_method_impl{PDMINETWORKNATCONFIG,pfnNotifyDnsChanged}
966 *
967 * We are notified that host's resolver configuration has changed. In
968 * the current setup we don't get any details and just reread that
969 * information ourselves.
970 */
971static DECLCALLBACK(void) drvNATNotifyDnsChanged(PPDMINETWORKNATCONFIG pInterface)
972{
973 PDRVNAT pThis = RT_FROM_MEMBER(pInterface, DRVNAT, INetworkNATCfg);
974 drvNATUpdateDNS(pThis, /* fFlapLink */ true);
975}
976
977
978#ifdef RT_OS_DARWIN
979/**
980 * Callback for the SystemConfiguration framework to notify us whenever the DNS
981 * server changes.
982 *
983 * @returns nothing.
984 * @param hDynStor The DynamicStore handle.
985 * @param hChangedKey Array of changed keys we watch for.
986 * @param pvUser Opaque user data (NAT driver instance).
987 */
988static DECLCALLBACK(void) drvNatDnsChanged(SCDynamicStoreRef hDynStor, CFArrayRef hChangedKeys, void *pvUser)
989{
990 PDRVNAT pThis = (PDRVNAT)pvUser;
991
992 Log2(("NAT: System configuration has changed\n"));
993
994 /* Check if any of parameters we are interested in were actually changed. If the size
995 * of hChangedKeys is 0, it means that SCDynamicStore has been restarted. */
996 if (hChangedKeys && CFArrayGetCount(hChangedKeys) > 0)
997 {
998 /* Look to the updated parameters in particular. */
999 CFStringRef pDNSKey = CFSTR("State:/Network/Global/DNS");
1000
1001 if (CFArrayContainsValue(hChangedKeys, CFRangeMake(0, CFArrayGetCount(hChangedKeys)), pDNSKey))
1002 {
1003 LogRel(("NAT: DNS servers changed, triggering reconnect\n"));
1004#if 0
1005 CFDictionaryRef hDnsDict = (CFDictionaryRef)SCDynamicStoreCopyValue(hDynStor, pDNSKey);
1006 if (hDnsDict)
1007 {
1008 CFArrayRef hArrAddresses = (CFArrayRef)CFDictionaryGetValue(hDnsDict, kSCPropNetDNSServerAddresses);
1009 if (hArrAddresses && CFArrayGetCount(hArrAddresses) > 0)
1010 {
1011 /* Dump DNS servers list. */
1012 for (int i = 0; i < CFArrayGetCount(hArrAddresses); i++)
1013 {
1014 CFStringRef pDNSAddrStr = (CFStringRef)CFArrayGetValueAtIndex(hArrAddresses, i);
1015 const char *pszDNSAddr = pDNSAddrStr ? CFStringGetCStringPtr(pDNSAddrStr, CFStringGetSystemEncoding()) : NULL;
1016 LogRel(("NAT: New DNS server#%d: %s\n", i, pszDNSAddr ? pszDNSAddr : "None"));
1017 }
1018 }
1019 else
1020 LogRel(("NAT: DNS server list is empty (1)\n"));
1021
1022 CFRelease(hDnsDict);
1023 }
1024 else
1025 LogRel(("NAT: DNS server list is empty (2)\n"));
1026#endif
1027 drvNATUpdateDNS(pThis, /* fFlapLink */ true);
1028 }
1029 else
1030 Log2(("NAT: No DNS changes detected\n"));
1031 }
1032 else
1033 Log2(("NAT: SCDynamicStore has been restarted\n"));
1034}
1035#endif
1036
1037/**
1038 * @interface_method_impl{PDMIBASE,pfnQueryInterface}
1039 */
1040static DECLCALLBACK(void *) drvNATQueryInterface(PPDMIBASE pInterface, const char *pszIID)
1041{
1042 PPDMDRVINS pDrvIns = PDMIBASE_2_PDMDRV(pInterface);
1043 PDRVNAT pThis = PDMINS_2_DATA(pDrvIns, PDRVNAT);
1044
1045 PDMIBASE_RETURN_INTERFACE(pszIID, PDMIBASE, &pDrvIns->IBase);
1046 PDMIBASE_RETURN_INTERFACE(pszIID, PDMINETWORKUP, &pThis->INetworkUp);
1047 PDMIBASE_RETURN_INTERFACE(pszIID, PDMINETWORKNATCONFIG, &pThis->INetworkNATCfg);
1048 return NULL;
1049}
1050
1051
1052/**
1053 * Get the MAC address into the slirp stack.
1054 *
1055 * Called by drvNATLoadDone and drvNATPowerOn.
1056 */
1057static void drvNATSetMac(PDRVNAT pThis)
1058{
1059 if (pThis->pIAboveConfig)
1060 {
1061 RTMAC Mac;
1062 pThis->pIAboveConfig->pfnGetMac(pThis->pIAboveConfig, &Mac);
1063 /* Re-activate the port forwarding. If */
1064 slirp_set_ethaddr_and_activate_port_forwarding(pThis->pNATState, Mac.au8, pThis->GuestIP);
1065 }
1066}
1067
1068
1069/**
1070 * After loading we have to pass the MAC address of the ethernet device to the slirp stack.
1071 * Otherwise the guest is not reachable until it performs a DHCP request or an ARP request
1072 * (usually done during guest boot).
1073 */
1074static DECLCALLBACK(int) drvNATLoadDone(PPDMDRVINS pDrvIns, PSSMHANDLE pSSMHandle)
1075{
1076 PDRVNAT pThis = PDMINS_2_DATA(pDrvIns, PDRVNAT);
1077 drvNATSetMac(pThis);
1078 return VINF_SUCCESS;
1079}
1080
1081
1082/**
1083 * Some guests might not use DHCP to retrieve an IP but use a static IP.
1084 */
1085static DECLCALLBACK(void) drvNATPowerOn(PPDMDRVINS pDrvIns)
1086{
1087 PDRVNAT pThis = PDMINS_2_DATA(pDrvIns, PDRVNAT);
1088 drvNATSetMac(pThis);
1089}
1090
1091
1092/**
1093 * @interface_method_impl{PDMDEVREG,pfnResume}
1094 */
1095static DECLCALLBACK(void) drvNATResume(PPDMDRVINS pDrvIns)
1096{
1097 PDRVNAT pThis = PDMINS_2_DATA(pDrvIns, PDRVNAT);
1098 VMRESUMEREASON enmReason = PDMDrvHlpVMGetResumeReason(pDrvIns);
1099
1100 switch (enmReason)
1101 {
1102 case VMRESUMEREASON_HOST_RESUME:
1103 bool fFlapLink;
1104#if HAVE_NOTIFICATION_FOR_DNS_UPDATE
1105 /* let event handler do it if necessary */
1106 fFlapLink = false;
1107#else
1108 /* XXX: when in doubt, use brute force */
1109 fFlapLink = true;
1110#endif
1111 drvNATUpdateDNS(pThis, fFlapLink);
1112 return;
1113 default: /* Ignore every other resume reason. */
1114 /* do nothing */
1115 return;
1116 }
1117}
1118
1119
1120static DECLCALLBACK(int) drvNATReinitializeHostNameResolving(PDRVNAT pThis)
1121{
1122 slirpReleaseDnsSettings(pThis->pNATState);
1123 slirpInitializeDnsSettings(pThis->pNATState);
1124 return VINF_SUCCESS;
1125}
1126
1127/**
1128 * This function at this stage could be called from two places, but both from non-NAT thread,
1129 * - drvNATResume (EMT?)
1130 * - drvNatDnsChanged (darwin, GUI or main) "listener"
1131 * When Main's interface IHost will support host network configuration change event on every host,
1132 * we won't call it from drvNATResume, but from listener of Main event in the similar way it done
1133 * for port-forwarding, and it wan't be on GUI/main thread, but on EMT thread only.
1134 *
1135 * Thread here is important, because we need to change DNS server list and domain name (+ perhaps,
1136 * search string) at runtime (VBOX_NAT_ENFORCE_INTERNAL_DNS_UPDATE), we can do it safely on NAT thread,
1137 * so with changing other variables (place where we handle update) the main mechanism of update
1138 * _won't_ be changed, the only thing will change is drop of fFlapLink parameter.
1139 */
1140DECLINLINE(void) drvNATUpdateDNS(PDRVNAT pThis, bool fFlapLink)
1141{
1142 int strategy = slirp_host_network_configuration_change_strategy_selector(pThis->pNATState);
1143 switch (strategy)
1144 {
1145
1146 case VBOX_NAT_DNS_DNSPROXY:
1147 {
1148 /**
1149 * XXX: Here or in _strategy_selector we should deal with network change
1150 * in "network change" scenario domain name change we have to update guest lease
1151 * forcibly.
1152 * Note at that built-in dhcp also updates DNS information on NAT thread.
1153 */
1154 /**
1155 * It's unsafe to to do it directly on non-NAT thread
1156 * so we schedule the worker and kick the NAT thread.
1157 */
1158 RTREQQUEUE hQueue = pThis->hSlirpReqQueue;
1159
1160 int rc = RTReqQueueCallEx(hQueue, NULL /*ppReq*/, 0 /*cMillies*/,
1161 RTREQFLAGS_VOID | RTREQFLAGS_NO_WAIT,
1162 (PFNRT)drvNATReinitializeHostNameResolving, 1, pThis);
1163 if (RT_SUCCESS(rc))
1164 drvNATNotifyNATThread(pThis, "drvNATUpdateDNS");
1165
1166 return;
1167 }
1168
1169 case VBOX_NAT_DNS_EXTERNAL:
1170 /*
1171 * Host resumed from a suspend and the network might have changed.
1172 * Disconnect the guest from the network temporarily to let it pick up the changes.
1173 */
1174
1175 if (fFlapLink)
1176 pThis->pIAboveConfig->pfnSetLinkState(pThis->pIAboveConfig,
1177 PDMNETWORKLINKSTATE_DOWN_RESUME);
1178 return;
1179
1180 case VBOX_NAT_DNS_HOSTRESOLVER:
1181 default:
1182 return;
1183 }
1184}
1185
1186
1187/**
1188 * Info handler.
1189 */
1190static DECLCALLBACK(void) drvNATInfo(PPDMDRVINS pDrvIns, PCDBGFINFOHLP pHlp, const char *pszArgs)
1191{
1192 PDRVNAT pThis = PDMINS_2_DATA(pDrvIns, PDRVNAT);
1193 slirp_info(pThis->pNATState, pHlp, pszArgs);
1194}
1195
1196#ifdef VBOX_WITH_DNSMAPPING_IN_HOSTRESOLVER
1197static int drvNATConstructDNSMappings(unsigned iInstance, PDRVNAT pThis, PCFGMNODE pMappingsCfg)
1198{
1199 int rc = VINF_SUCCESS;
1200 LogFlowFunc(("ENTER: iInstance:%d\n", iInstance));
1201 for (PCFGMNODE pNode = CFGMR3GetFirstChild(pMappingsCfg); pNode; pNode = CFGMR3GetNextChild(pNode))
1202 {
1203 if (!CFGMR3AreValuesValid(pNode, "HostName\0HostNamePattern\0HostIP\0"))
1204 return PDMDRV_SET_ERROR(pThis->pDrvIns, VERR_PDM_DRVINS_UNKNOWN_CFG_VALUES,
1205 N_("Unknown configuration in dns mapping"));
1206 char szHostNameOrPattern[255];
1207 bool fMatch = false; /* false used for equal matching, and true if wildcard pattern is used. */
1208 RT_ZERO(szHostNameOrPattern);
1209 GET_STRING(rc, pThis, pNode, "HostName", szHostNameOrPattern[0], sizeof(szHostNameOrPattern));
1210 if (rc == VERR_CFGM_VALUE_NOT_FOUND)
1211 {
1212 GET_STRING(rc, pThis, pNode, "HostNamePattern", szHostNameOrPattern[0], sizeof(szHostNameOrPattern));
1213 if (rc == VERR_CFGM_VALUE_NOT_FOUND)
1214 {
1215 char szNodeName[225];
1216 RT_ZERO(szNodeName);
1217 CFGMR3GetName(pNode, szNodeName, sizeof(szNodeName));
1218 LogRel(("NAT: Neither 'HostName' nor 'HostNamePattern' is specified for mapping %s\n", szNodeName));
1219 continue;
1220 }
1221 fMatch = true;
1222 }
1223 struct in_addr HostIP;
1224 GETIP_DEF(rc, pThis, pNode, HostIP, INADDR_ANY);
1225 if (rc == VERR_CFGM_VALUE_NOT_FOUND)
1226 {
1227 LogRel(("NAT: DNS mapping %s is ignored (address not pointed)\n", szHostNameOrPattern));
1228 continue;
1229 }
1230 slirp_add_host_resolver_mapping(pThis->pNATState, fMatch ? NULL : szHostNameOrPattern, fMatch ? szHostNameOrPattern : NULL, HostIP.s_addr);
1231 }
1232 LogFlowFunc(("LEAVE: %Rrc\n", rc));
1233 return rc;
1234}
1235#endif /* !VBOX_WITH_DNSMAPPING_IN_HOSTRESOLVER */
1236
1237
1238/**
1239 * Sets up the redirectors.
1240 *
1241 * @returns VBox status code.
1242 * @param pCfg The configuration handle.
1243 */
1244static int drvNATConstructRedir(unsigned iInstance, PDRVNAT pThis, PCFGMNODE pCfg, PRTNETADDRIPV4 pNetwork)
1245{
1246 RTMAC Mac;
1247 RT_ZERO(Mac); /* can't get MAC here */
1248
1249 /*
1250 * Enumerate redirections.
1251 */
1252 for (PCFGMNODE pNode = CFGMR3GetFirstChild(pCfg); pNode; pNode = CFGMR3GetNextChild(pNode))
1253 {
1254#ifdef VBOX_WITH_DNSMAPPING_IN_HOSTRESOLVER
1255 char szNodeName[32];
1256 CFGMR3GetName(pNode, szNodeName, 32);
1257 if ( !RTStrICmp(szNodeName, "HostResolverMappings")
1258 || !RTStrICmp(szNodeName, "AttachedDriver"))
1259 continue;
1260#endif
1261 /*
1262 * Validate the port forwarding config.
1263 */
1264 if (!CFGMR3AreValuesValid(pNode, "Protocol\0UDP\0HostPort\0GuestPort\0GuestIP\0BindIP\0"))
1265 return PDMDRV_SET_ERROR(pThis->pDrvIns, VERR_PDM_DRVINS_UNKNOWN_CFG_VALUES,
1266 N_("Unknown configuration in port forwarding"));
1267
1268 /* protocol type */
1269 bool fUDP;
1270 char szProtocol[32];
1271 int rc;
1272 GET_STRING(rc, pThis, pNode, "Protocol", szProtocol[0], sizeof(szProtocol));
1273 if (rc == VERR_CFGM_VALUE_NOT_FOUND)
1274 {
1275 fUDP = false;
1276 GET_BOOL(rc, pThis, pNode, "UDP", fUDP);
1277 }
1278 else if (RT_SUCCESS(rc))
1279 {
1280 if (!RTStrICmp(szProtocol, "TCP"))
1281 fUDP = false;
1282 else if (!RTStrICmp(szProtocol, "UDP"))
1283 fUDP = true;
1284 else
1285 return PDMDrvHlpVMSetError(pThis->pDrvIns, VERR_INVALID_PARAMETER, RT_SRC_POS,
1286 N_("NAT#%d: Invalid configuration value for \"Protocol\": \"%s\""),
1287 iInstance, szProtocol);
1288 }
1289 else
1290 return PDMDrvHlpVMSetError(pThis->pDrvIns, rc, RT_SRC_POS,
1291 N_("NAT#%d: configuration query for \"Protocol\" failed"),
1292 iInstance);
1293 /* host port */
1294 int32_t iHostPort;
1295 GET_S32_STRICT(rc, pThis, pNode, "HostPort", iHostPort);
1296
1297 /* guest port */
1298 int32_t iGuestPort;
1299 GET_S32_STRICT(rc, pThis, pNode, "GuestPort", iGuestPort);
1300
1301 /* guest address */
1302 struct in_addr GuestIP;
1303 GETIP_DEF(rc, pThis, pNode, GuestIP, RT_H2N_U32(pNetwork->u | CTL_GUEST));
1304
1305 /* Store the guest IP for re-establishing the port-forwarding rules. Note that GuestIP
1306 * is not documented. Without */
1307 if (pThis->GuestIP == INADDR_ANY)
1308 pThis->GuestIP = GuestIP.s_addr;
1309
1310 /*
1311 * Call slirp about it.
1312 */
1313 struct in_addr BindIP;
1314 GETIP_DEF(rc, pThis, pNode, BindIP, INADDR_ANY);
1315 if (slirp_add_redirect(pThis->pNATState, fUDP, BindIP, iHostPort, GuestIP, iGuestPort, Mac.au8) < 0)
1316 return PDMDrvHlpVMSetError(pThis->pDrvIns, VERR_NAT_REDIR_SETUP, RT_SRC_POS,
1317 N_("NAT#%d: configuration error: failed to set up "
1318 "redirection of %d to %d. Probably a conflict with "
1319 "existing services or other rules"), iInstance, iHostPort,
1320 iGuestPort);
1321 } /* for each redir rule */
1322
1323 return VINF_SUCCESS;
1324}
1325
1326
1327/**
1328 * Destruct a driver instance.
1329 *
1330 * Most VM resources are freed by the VM. This callback is provided so that any non-VM
1331 * resources can be freed correctly.
1332 *
1333 * @param pDrvIns The driver instance data.
1334 */
1335static DECLCALLBACK(void) drvNATDestruct(PPDMDRVINS pDrvIns)
1336{
1337 PDRVNAT pThis = PDMINS_2_DATA(pDrvIns, PDRVNAT);
1338 LogFlow(("drvNATDestruct:\n"));
1339 PDMDRV_CHECK_VERSIONS_RETURN_VOID(pDrvIns);
1340
1341 if (pThis->pNATState)
1342 {
1343 slirp_term(pThis->pNATState);
1344 slirp_deregister_statistics(pThis->pNATState, pDrvIns);
1345#ifdef VBOX_WITH_STATISTICS
1346# define DRV_PROFILE_COUNTER(name, dsc) DEREGISTER_COUNTER(name, pThis)
1347# define DRV_COUNTING_COUNTER(name, dsc) DEREGISTER_COUNTER(name, pThis)
1348# include "counters.h"
1349#endif
1350 pThis->pNATState = NULL;
1351 }
1352
1353 RTReqQueueDestroy(pThis->hSlirpReqQueue);
1354 pThis->hSlirpReqQueue = NIL_RTREQQUEUE;
1355
1356 RTReqQueueDestroy(pThis->hUrgRecvReqQueue);
1357 pThis->hUrgRecvReqQueue = NIL_RTREQQUEUE;
1358
1359 RTSemEventDestroy(pThis->EventRecv);
1360 pThis->EventRecv = NIL_RTSEMEVENT;
1361
1362 RTSemEventDestroy(pThis->EventUrgRecv);
1363 pThis->EventUrgRecv = NIL_RTSEMEVENT;
1364
1365 if (RTCritSectIsInitialized(&pThis->DevAccessLock))
1366 RTCritSectDelete(&pThis->DevAccessLock);
1367
1368 if (RTCritSectIsInitialized(&pThis->XmitLock))
1369 RTCritSectDelete(&pThis->XmitLock);
1370
1371#ifdef RT_OS_DARWIN
1372 /* Cleanup the DNS watcher. */
1373 CFRunLoopRef hRunLoopMain = CFRunLoopGetMain();
1374 CFRetain(hRunLoopMain);
1375 CFRunLoopRemoveSource(hRunLoopMain, pThis->hRunLoopSrcDnsWatcher, kCFRunLoopCommonModes);
1376 CFRelease(hRunLoopMain);
1377 CFRelease(pThis->hRunLoopSrcDnsWatcher);
1378 pThis->hRunLoopSrcDnsWatcher = NULL;
1379#endif
1380}
1381
1382
1383/**
1384 * Construct a NAT network transport driver instance.
1385 *
1386 * @copydoc FNPDMDRVCONSTRUCT
1387 */
1388static DECLCALLBACK(int) drvNATConstruct(PPDMDRVINS pDrvIns, PCFGMNODE pCfg, uint32_t fFlags)
1389{
1390 PDRVNAT pThis = PDMINS_2_DATA(pDrvIns, PDRVNAT);
1391 LogFlow(("drvNATConstruct:\n"));
1392 PDMDRV_CHECK_VERSIONS_RETURN(pDrvIns);
1393
1394 /*
1395 * Init the static parts.
1396 */
1397 pThis->pDrvIns = pDrvIns;
1398 pThis->pNATState = NULL;
1399 pThis->pszTFTPPrefix = NULL;
1400 pThis->pszBootFile = NULL;
1401 pThis->pszNextServer = NULL;
1402 pThis->hSlirpReqQueue = NIL_RTREQQUEUE;
1403 pThis->hUrgRecvReqQueue = NIL_RTREQQUEUE;
1404 pThis->EventRecv = NIL_RTSEMEVENT;
1405 pThis->EventUrgRecv = NIL_RTSEMEVENT;
1406#ifdef RT_OS_DARWIN
1407 pThis->hRunLoopSrcDnsWatcher = NULL;
1408#endif
1409
1410 /* IBase */
1411 pDrvIns->IBase.pfnQueryInterface = drvNATQueryInterface;
1412
1413 /* INetwork */
1414 pThis->INetworkUp.pfnBeginXmit = drvNATNetworkUp_BeginXmit;
1415 pThis->INetworkUp.pfnAllocBuf = drvNATNetworkUp_AllocBuf;
1416 pThis->INetworkUp.pfnFreeBuf = drvNATNetworkUp_FreeBuf;
1417 pThis->INetworkUp.pfnSendBuf = drvNATNetworkUp_SendBuf;
1418 pThis->INetworkUp.pfnEndXmit = drvNATNetworkUp_EndXmit;
1419 pThis->INetworkUp.pfnSetPromiscuousMode = drvNATNetworkUp_SetPromiscuousMode;
1420 pThis->INetworkUp.pfnNotifyLinkChanged = drvNATNetworkUp_NotifyLinkChanged;
1421
1422 /* NAT engine configuration */
1423 pThis->INetworkNATCfg.pfnRedirectRuleCommand = drvNATNetworkNatConfig_RedirectRuleCommand;
1424#if HAVE_NOTIFICATION_FOR_DNS_UPDATE && !defined(RT_OS_DARWIN)
1425 /*
1426 * On OS X we stick to the old OS X specific notifications for
1427 * now. Elsewhere use IHostNameResolutionConfigurationChangeEvent
1428 * by enbaling HAVE_NOTIFICATION_FOR_DNS_UPDATE in libslirp.h.
1429 * This code is still in a bit of flux and is implemented and
1430 * enabled in steps to simplify more conservative backporting.
1431 */
1432 pThis->INetworkNATCfg.pfnNotifyDnsChanged = drvNATNotifyDnsChanged;
1433#else
1434 pThis->INetworkNATCfg.pfnNotifyDnsChanged = NULL;
1435#endif
1436
1437 /*
1438 * Validate the config.
1439 */
1440 if (!CFGMR3AreValuesValid(pCfg,
1441 "PassDomain\0TFTPPrefix\0BootFile\0Network"
1442 "\0NextServer\0DNSProxy\0BindIP\0UseHostResolver\0"
1443 "SlirpMTU\0AliasMode\0"
1444 "SockRcv\0SockSnd\0TcpRcv\0TcpSnd\0"
1445 "ICMPCacheLimit\0"
1446 "SoMaxConnection\0"
1447#ifdef VBOX_WITH_DNSMAPPING_IN_HOSTRESOLVER
1448 "HostResolverMappings\0"
1449#endif
1450 ))
1451 return PDMDRV_SET_ERROR(pDrvIns, VERR_PDM_DRVINS_UNKNOWN_CFG_VALUES,
1452 N_("Unknown NAT configuration option, only supports PassDomain,"
1453 " TFTPPrefix, BootFile and Network"));
1454
1455 /*
1456 * Get the configuration settings.
1457 */
1458 int rc;
1459 bool fPassDomain = true;
1460 GET_BOOL(rc, pThis, pCfg, "PassDomain", fPassDomain);
1461
1462 GET_STRING_ALLOC(rc, pThis, pCfg, "TFTPPrefix", pThis->pszTFTPPrefix);
1463 GET_STRING_ALLOC(rc, pThis, pCfg, "BootFile", pThis->pszBootFile);
1464 GET_STRING_ALLOC(rc, pThis, pCfg, "NextServer", pThis->pszNextServer);
1465
1466 int fDNSProxy = 0;
1467 GET_S32(rc, pThis, pCfg, "DNSProxy", fDNSProxy);
1468 int fUseHostResolver = 0;
1469 GET_S32(rc, pThis, pCfg, "UseHostResolver", fUseHostResolver);
1470 int MTU = 1500;
1471 GET_S32(rc, pThis, pCfg, "SlirpMTU", MTU);
1472 int i32AliasMode = 0;
1473 int i32MainAliasMode = 0;
1474 GET_S32(rc, pThis, pCfg, "AliasMode", i32MainAliasMode);
1475 int iIcmpCacheLimit = 100;
1476 GET_S32(rc, pThis, pCfg, "ICMPCacheLimit", iIcmpCacheLimit);
1477
1478 i32AliasMode |= (i32MainAliasMode & 0x1 ? 0x1 : 0);
1479 i32AliasMode |= (i32MainAliasMode & 0x2 ? 0x40 : 0);
1480 i32AliasMode |= (i32MainAliasMode & 0x4 ? 0x4 : 0);
1481 int i32SoMaxConn = 10;
1482 GET_S32(rc, pThis, pCfg, "SoMaxConnection", i32SoMaxConn);
1483 /*
1484 * Query the network port interface.
1485 */
1486 pThis->pIAboveNet = PDMIBASE_QUERY_INTERFACE(pDrvIns->pUpBase, PDMINETWORKDOWN);
1487 if (!pThis->pIAboveNet)
1488 return PDMDRV_SET_ERROR(pDrvIns, VERR_PDM_MISSING_INTERFACE_ABOVE,
1489 N_("Configuration error: the above device/driver didn't "
1490 "export the network port interface"));
1491 pThis->pIAboveConfig = PDMIBASE_QUERY_INTERFACE(pDrvIns->pUpBase, PDMINETWORKCONFIG);
1492 if (!pThis->pIAboveConfig)
1493 return PDMDRV_SET_ERROR(pDrvIns, VERR_PDM_MISSING_INTERFACE_ABOVE,
1494 N_("Configuration error: the above device/driver didn't "
1495 "export the network config interface"));
1496
1497 /* Generate a network address for this network card. */
1498 char szNetwork[32]; /* xxx.xxx.xxx.xxx/yy */
1499 GET_STRING(rc, pThis, pCfg, "Network", szNetwork[0], sizeof(szNetwork));
1500 if (rc == VERR_CFGM_VALUE_NOT_FOUND)
1501 return PDMDrvHlpVMSetError(pDrvIns, rc, RT_SRC_POS, N_("NAT%d: Configuration error: missing network"),
1502 pDrvIns->iInstance);
1503
1504 RTNETADDRIPV4 Network, Netmask;
1505
1506 rc = RTCidrStrToIPv4(szNetwork, &Network, &Netmask);
1507 if (RT_FAILURE(rc))
1508 return PDMDrvHlpVMSetError(pDrvIns, rc, RT_SRC_POS,
1509 N_("NAT#%d: Configuration error: network '%s' describes not a valid IPv4 network"),
1510 pDrvIns->iInstance, szNetwork);
1511
1512 /*
1513 * Initialize slirp.
1514 */
1515 rc = slirp_init(&pThis->pNATState, RT_H2N_U32(Network.u), Netmask.u,
1516 fPassDomain, !!fUseHostResolver, i32AliasMode,
1517 iIcmpCacheLimit, pThis);
1518 if (RT_SUCCESS(rc))
1519 {
1520 slirp_set_dhcp_TFTP_prefix(pThis->pNATState, pThis->pszTFTPPrefix);
1521 slirp_set_dhcp_TFTP_bootfile(pThis->pNATState, pThis->pszBootFile);
1522 slirp_set_dhcp_next_server(pThis->pNATState, pThis->pszNextServer);
1523 slirp_set_dhcp_dns_proxy(pThis->pNATState, !!fDNSProxy);
1524 slirp_set_mtu(pThis->pNATState, MTU);
1525 slirp_set_somaxconn(pThis->pNATState, i32SoMaxConn);
1526 char *pszBindIP = NULL;
1527 GET_STRING_ALLOC(rc, pThis, pCfg, "BindIP", pszBindIP);
1528 rc = slirp_set_binding_address(pThis->pNATState, pszBindIP);
1529 if (rc != 0 && pszBindIP && *pszBindIP)
1530 LogRel(("NAT: Value of BindIP has been ignored\n"));
1531
1532 if(pszBindIP != NULL)
1533 MMR3HeapFree(pszBindIP);
1534#define SLIRP_SET_TUNING_VALUE(name, setter) \
1535 do \
1536 { \
1537 int len = 0; \
1538 rc = CFGMR3QueryS32(pCfg, name, &len); \
1539 if (RT_SUCCESS(rc)) \
1540 setter(pThis->pNATState, len); \
1541 } while(0)
1542
1543 SLIRP_SET_TUNING_VALUE("SockRcv", slirp_set_rcvbuf);
1544 SLIRP_SET_TUNING_VALUE("SockSnd", slirp_set_sndbuf);
1545 SLIRP_SET_TUNING_VALUE("TcpRcv", slirp_set_tcp_rcvspace);
1546 SLIRP_SET_TUNING_VALUE("TcpSnd", slirp_set_tcp_sndspace);
1547
1548 slirp_register_statistics(pThis->pNATState, pDrvIns);
1549#ifdef VBOX_WITH_STATISTICS
1550# define DRV_PROFILE_COUNTER(name, dsc) REGISTER_COUNTER(name, pThis, STAMTYPE_PROFILE, STAMUNIT_TICKS_PER_CALL, dsc)
1551# define DRV_COUNTING_COUNTER(name, dsc) REGISTER_COUNTER(name, pThis, STAMTYPE_COUNTER, STAMUNIT_COUNT, dsc)
1552# include "counters.h"
1553#endif
1554
1555#ifdef VBOX_WITH_DNSMAPPING_IN_HOSTRESOLVER
1556 PCFGMNODE pMappingsCfg = CFGMR3GetChild(pCfg, "HostResolverMappings");
1557
1558 if (pMappingsCfg)
1559 {
1560 rc = drvNATConstructDNSMappings(pDrvIns->iInstance, pThis, pMappingsCfg);
1561 AssertRC(rc);
1562 }
1563#endif
1564 rc = drvNATConstructRedir(pDrvIns->iInstance, pThis, pCfg, &Network);
1565 if (RT_SUCCESS(rc))
1566 {
1567 /*
1568 * Register a load done notification to get the MAC address into the slirp
1569 * engine after we loaded a guest state.
1570 */
1571 rc = PDMDrvHlpSSMRegisterLoadDone(pDrvIns, drvNATLoadDone);
1572 AssertLogRelRCReturn(rc, rc);
1573
1574 rc = RTReqQueueCreate(&pThis->hSlirpReqQueue);
1575 AssertLogRelRCReturn(rc, rc);
1576
1577 rc = RTReqQueueCreate(&pThis->hRecvReqQueue);
1578 AssertLogRelRCReturn(rc, rc);
1579
1580 rc = RTReqQueueCreate(&pThis->hUrgRecvReqQueue);
1581 AssertLogRelRCReturn(rc, rc);
1582
1583 rc = PDMDrvHlpThreadCreate(pDrvIns, &pThis->pRecvThread, pThis, drvNATRecv,
1584 drvNATRecvWakeup, 128 * _1K, RTTHREADTYPE_IO, "NATRX");
1585 AssertRCReturn(rc, rc);
1586
1587 rc = RTSemEventCreate(&pThis->EventRecv);
1588 AssertRCReturn(rc, rc);
1589
1590 rc = PDMDrvHlpThreadCreate(pDrvIns, &pThis->pUrgRecvThread, pThis, drvNATUrgRecv,
1591 drvNATUrgRecvWakeup, 128 * _1K, RTTHREADTYPE_IO, "NATURGRX");
1592 AssertRCReturn(rc, rc);
1593
1594 rc = RTSemEventCreate(&pThis->EventRecv);
1595 AssertRCReturn(rc, rc);
1596
1597 rc = RTSemEventCreate(&pThis->EventUrgRecv);
1598 AssertRCReturn(rc, rc);
1599
1600 rc = RTCritSectInit(&pThis->DevAccessLock);
1601 AssertRCReturn(rc, rc);
1602
1603 rc = RTCritSectInit(&pThis->XmitLock);
1604 AssertRCReturn(rc, rc);
1605
1606 char szTmp[128];
1607 RTStrPrintf(szTmp, sizeof(szTmp), "nat%d", pDrvIns->iInstance);
1608 PDMDrvHlpDBGFInfoRegister(pDrvIns, szTmp, "NAT info.", drvNATInfo);
1609
1610#ifndef RT_OS_WINDOWS
1611 /*
1612 * Create the control pipe.
1613 */
1614 rc = RTPipeCreate(&pThis->hPipeRead, &pThis->hPipeWrite, 0 /*fFlags*/);
1615 AssertRCReturn(rc, rc);
1616#else
1617 pThis->hWakeupEvent = CreateEvent(NULL, FALSE, FALSE, NULL); /* auto-reset event */
1618 slirp_register_external_event(pThis->pNATState, pThis->hWakeupEvent,
1619 VBOX_WAKEUP_EVENT_INDEX);
1620#endif
1621
1622 rc = PDMDrvHlpThreadCreate(pDrvIns, &pThis->pSlirpThread, pThis, drvNATAsyncIoThread,
1623 drvNATAsyncIoWakeup, 128 * _1K, RTTHREADTYPE_IO, "NAT");
1624 AssertRCReturn(rc, rc);
1625
1626 pThis->enmLinkState = pThis->enmLinkStateWant = PDMNETWORKLINKSTATE_UP;
1627
1628#ifdef RT_OS_DARWIN
1629 /* Set up a watcher which notifies us everytime the DNS server changes. */
1630 int rc2 = VINF_SUCCESS;
1631 SCDynamicStoreContext SCDynStorCtx;
1632
1633 SCDynStorCtx.version = 0;
1634 SCDynStorCtx.info = pThis;
1635 SCDynStorCtx.retain = NULL;
1636 SCDynStorCtx.release = NULL;
1637 SCDynStorCtx.copyDescription = NULL;
1638
1639 SCDynamicStoreRef hDynStor = SCDynamicStoreCreate(NULL, CFSTR("org.virtualbox.drvnat"), drvNatDnsChanged, &SCDynStorCtx);
1640 if (hDynStor)
1641 {
1642 CFRunLoopSourceRef hRunLoopSrc = SCDynamicStoreCreateRunLoopSource(NULL, hDynStor, 0);
1643 if (hRunLoopSrc)
1644 {
1645 CFStringRef aWatchKeys[] =
1646 {
1647 CFSTR("State:/Network/Global/DNS")
1648 };
1649 CFArrayRef hArray = CFArrayCreate(NULL, (const void **)aWatchKeys, 1, &kCFTypeArrayCallBacks);
1650
1651 if (hArray)
1652 {
1653 if (SCDynamicStoreSetNotificationKeys(hDynStor, hArray, NULL))
1654 {
1655 CFRunLoopRef hRunLoopMain = CFRunLoopGetMain();
1656 CFRetain(hRunLoopMain);
1657 CFRunLoopAddSource(hRunLoopMain, hRunLoopSrc, kCFRunLoopCommonModes);
1658 CFRelease(hRunLoopMain);
1659 pThis->hRunLoopSrcDnsWatcher = hRunLoopSrc;
1660 }
1661 else
1662 rc2 = VERR_NO_MEMORY;
1663
1664 CFRelease(hArray);
1665 }
1666 else
1667 rc2 = VERR_NO_MEMORY;
1668
1669 if (RT_FAILURE(rc2)) /* Keep the runloop source referenced for destruction. */
1670 CFRelease(hRunLoopSrc);
1671 }
1672 CFRelease(hDynStor);
1673 }
1674 else
1675 rc2 = VERR_NO_MEMORY;
1676
1677 if (RT_FAILURE(rc2))
1678 LogRel(("NAT#%d: Failed to install DNS change notifier. The guest might loose DNS access when switching networks on the host\n",
1679 pDrvIns->iInstance));
1680#endif
1681
1682 /* might return VINF_NAT_DNS */
1683 return rc;
1684 }
1685
1686 /* failure path */
1687 slirp_term(pThis->pNATState);
1688 pThis->pNATState = NULL;
1689 }
1690 else
1691 {
1692 PDMDRV_SET_ERROR(pDrvIns, rc, N_("Unknown error during NAT networking setup: "));
1693 AssertMsgFailed(("Add error message for rc=%d (%Rrc)\n", rc, rc));
1694 }
1695
1696 return rc;
1697}
1698
1699
1700/**
1701 * NAT network transport driver registration record.
1702 */
1703const PDMDRVREG g_DrvNAT =
1704{
1705 /* u32Version */
1706 PDM_DRVREG_VERSION,
1707 /* szName */
1708 "NAT",
1709 /* szRCMod */
1710 "",
1711 /* szR0Mod */
1712 "",
1713 /* pszDescription */
1714 "NAT Network Transport Driver",
1715 /* fFlags */
1716 PDM_DRVREG_FLAGS_HOST_BITS_DEFAULT,
1717 /* fClass. */
1718 PDM_DRVREG_CLASS_NETWORK,
1719 /* cMaxInstances */
1720 ~0U,
1721 /* cbInstance */
1722 sizeof(DRVNAT),
1723 /* pfnConstruct */
1724 drvNATConstruct,
1725 /* pfnDestruct */
1726 drvNATDestruct,
1727 /* pfnRelocate */
1728 NULL,
1729 /* pfnIOCtl */
1730 NULL,
1731 /* pfnPowerOn */
1732 drvNATPowerOn,
1733 /* pfnReset */
1734 NULL,
1735 /* pfnSuspend */
1736 NULL,
1737 /* pfnResume */
1738 drvNATResume,
1739 /* pfnAttach */
1740 NULL,
1741 /* pfnDetach */
1742 NULL,
1743 /* pfnPowerOff */
1744 NULL,
1745 /* pfnSoftReset */
1746 NULL,
1747 /* u32EndVersion */
1748 PDM_DRVREG_VERSION
1749};
1750
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