VirtualBox

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

Last change on this file since 91631 was 88553, checked in by vboxsync, 4 years ago

NAT: Do not attempt to segment frames with invalid GSO

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