VirtualBox

source: vbox/trunk/src/VBox/Devices/Network/DrvNATlibslirp.cpp@ 108236

最後變更 在這個檔案從108236是 107983,由 vboxsync 提交於 6 週 前

Devices/Network: Fix port forward fail causing vm crash in debug build. bugref:10268

  • 屬性 svn:eol-style 設為 native
  • 屬性 svn:keywords 設為 Author Date Id Revision
檔案大小: 65.2 KB
 
1/* $Id: DrvNATlibslirp.cpp 107983 2025-01-30 05:09:07Z vboxsync $ */
2/** @file
3 * DrvNATlibslirp - NATlibslirp network transport driver.
4 */
5
6/*
7 * Copyright (C) 2022-2024 Oracle and/or its affiliates.
8 *
9 * This file is part of VirtualBox base platform packages, as
10 * available from https://www.alldomusa.eu.org.
11 *
12 * This program is free software; you can redistribute it and/or
13 * modify it under the terms of the GNU General Public License
14 * as published by the Free Software Foundation, in version 3 of the
15 * License.
16 *
17 * This program is distributed in the hope that it will be useful, but
18 * WITHOUT ANY WARRANTY; without even the implied warranty of
19 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
20 * General Public License for more details.
21 *
22 * You should have received a copy of the GNU General Public License
23 * along with this program; if not, see <https://www.gnu.org/licenses>.
24 *
25 * SPDX-License-Identifier: GPL-3.0-only
26 */
27
28
29/*********************************************************************************************************************************
30* Header Files *
31*********************************************************************************************************************************/
32#define LOG_GROUP LOG_GROUP_DRV_NAT
33#define RTNET_INCL_IN_ADDR
34#include "VBoxDD.h"
35
36#ifdef RT_OS_WINDOWS
37# include <iprt/win/winsock2.h>
38# include <iprt/win/ws2tcpip.h>
39# include "winutils.h"
40# define inet_aton(x, y) inet_pton(2, x, y)
41# define AF_INET6 23
42#endif
43
44#include <libslirp.h>
45
46#include <VBox/vmm/dbgf.h>
47#include <VBox/vmm/pdmdrv.h>
48#include <VBox/vmm/pdmnetifs.h>
49#include <VBox/vmm/pdmnetinline.h>
50
51#ifndef RT_OS_WINDOWS
52# include <unistd.h>
53# include <fcntl.h>
54# include <poll.h>
55# include <errno.h>
56#endif
57
58#ifdef RT_OS_FREEBSD
59# include <netinet/in.h>
60#endif
61
62#include <iprt/asm.h>
63#include <iprt/assert.h>
64#include <iprt/critsect.h>
65#include <iprt/cidr.h>
66#include <iprt/file.h>
67#include <limits.h>
68#include <iprt/mem.h>
69#include <iprt/net.h>
70#include <iprt/pipe.h>
71#include <iprt/string.h>
72#include <iprt/stream.h>
73#include <iprt/time.h>
74#include <iprt/uuid.h>
75
76#include <iprt/asm.h>
77
78#include <iprt/semaphore.h>
79#include <iprt/req.h>
80#ifdef RT_OS_DARWIN
81# include <SystemConfiguration/SystemConfiguration.h>
82# include <CoreFoundation/CoreFoundation.h>
83#endif
84
85#define COUNTERS_INIT
86#include "slirp/counters.h"
87#include "slirp/resolv_conf_parser.h"
88
89
90/*********************************************************************************************************************************
91* Defined Constants And Macros *
92*********************************************************************************************************************************/
93#define DRVNAT_MAXFRAMESIZE (16 * 1024)
94/** The maximum (default) poll/WSAPoll timeout. */
95#define DRVNAT_DEFAULT_TIMEOUT (int)RT_MS_1HOUR
96#define MAX_IP_ADDRESS_STR_LEN_W_NULL 16
97
98/** @todo r=bird: this is a load of weirdness... 'extradata' != cfgm. */
99#define GET_EXTRADATA(pdrvins, node, name, rc, type, type_name, var) \
100 do { \
101 (rc) = (pdrvins)->pHlpR3->pfnCFGMQuery ## type((node), name, &(var)); \
102 if (RT_FAILURE((rc)) && (rc) != VERR_CFGM_VALUE_NOT_FOUND) \
103 return PDMDrvHlpVMSetError((pdrvins), (rc), RT_SRC_POS, \
104 N_("NAT#%d: configuration query for \"" name "\" " #type_name " failed"), \
105 (pdrvins)->iInstance); \
106 } while (0)
107
108#define GET_ED_STRICT(pdrvins, node, name, rc, type, type_name, var) \
109 do { \
110 (rc) = (pdrvins)->pHlpR3->pfnCFGMQuery ## type((node), name, &(var)); \
111 if (RT_FAILURE((rc))) \
112 return PDMDrvHlpVMSetError((pdrvins), (rc), RT_SRC_POS, \
113 N_("NAT#%d: configuration query for \"" name "\" " #type_name " failed"), \
114 (pdrvins)->iInstance); \
115 } while (0)
116
117#define GET_EXTRADATA_N(pdrvins, node, name, rc, type, type_name, var, var_size) \
118 do { \
119 (rc) = (pdrvins)->pHlpR3->pfnCFGMQuery ## type((node), name, &(var), var_size); \
120 if (RT_FAILURE((rc)) && (rc) != VERR_CFGM_VALUE_NOT_FOUND) \
121 return PDMDrvHlpVMSetError((pdrvins), (rc), RT_SRC_POS, \
122 N_("NAT#%d: configuration query for \"" name "\" " #type_name " failed"), \
123 (pdrvins)->iInstance); \
124 } while (0)
125
126#define GET_BOOL(rc, pdrvins, node, name, var) \
127 GET_EXTRADATA(pdrvins, node, name, (rc), Bool, bolean, (var))
128#define GET_STRING(rc, pdrvins, node, name, var, var_size) \
129 GET_EXTRADATA_N(pdrvins, node, name, (rc), String, string, (var), (var_size))
130#define GET_STRING_ALLOC(rc, pdrvins, node, name, var) \
131 GET_EXTRADATA(pdrvins, node, name, (rc), StringAlloc, string, (var))
132#define GET_U16_STRICT(rc, pdrvins, node, name, var) \
133 GET_ED_STRICT(pdrvins, node, name, (rc), U16, int, (var))
134#define GET_S32(rc, pdrvins, node, name, var) \
135 GET_EXTRADATA(pdrvins, node, name, (rc), S32, int, (var))
136#define GET_U32(rc, pdrvins, node, name, var) \
137 GET_EXTRADATA(pdrvins, node, name, (rc), U32, int, (var))
138
139#define DO_GET_IP(rc, node, instance, status, x) \
140 do { \
141 char sz##x[32]; \
142 GET_STRING((rc), (node), (instance), #x, sz ## x[0], sizeof(sz ## x)); \
143 if (rc != VERR_CFGM_VALUE_NOT_FOUND) \
144 (status) = inet_aton(sz ## x, &x); \
145 } while (0)
146
147#define GETIP_DEF(rc, node, instance, x, def) \
148 do \
149 { \
150 int status = 0; \
151 DO_GET_IP((rc), (node), (instance), status, x); \
152 if (status == 0 || rc == VERR_CFGM_VALUE_NOT_FOUND) \
153 x.s_addr = def; \
154 } while (0)
155
156
157/*********************************************************************************************************************************
158* Structures and Typedefs *
159*********************************************************************************************************************************/
160/** Slirp Timer */
161typedef struct slirpTimer
162{
163 struct slirpTimer *next;
164 /** The time deadline (milliseconds, RTTimeMilliTS). */
165 int64_t msExpire;
166 SlirpTimerCb pHandler;
167 void *opaque;
168} SlirpTimer;
169
170/**
171 * Main state of Libslirp NAT
172 */
173typedef struct SlirpState
174{
175 unsigned int nsock;
176
177 Slirp *pSlirp;
178 struct pollfd *polls;
179
180 /** Num Polls (not bytes) */
181 unsigned int uPollCap = 0;
182
183 /** List of timers (in reverse creation order).
184 * @note There is currently only one libslirp timer (v4.8 / 2025-01-16). */
185 SlirpTimer *pTimerHead;
186 bool fPassDomain;
187} SlirpState;
188typedef SlirpState *pSlirpState;
189
190/**
191 * NAT network transport driver instance data.
192 *
193 * @implements PDMINETWORKUP
194 */
195typedef struct DRVNAT
196{
197 /** The network interface. */
198 PDMINETWORKUP INetworkUp;
199 /** The network NAT Engine configuration. */
200 PDMINETWORKNATCONFIG INetworkNATCfg;
201 /** The port we're attached to. */
202 PPDMINETWORKDOWN pIAboveNet;
203 /** The network config of the port we're attached to. */
204 PPDMINETWORKCONFIG pIAboveConfig;
205 /** Pointer to the driver instance. */
206 PPDMDRVINS pDrvIns;
207 /** Link state */
208 PDMNETWORKLINKSTATE enmLinkState;
209 /** NAT state */
210 pSlirpState pNATState;
211 /** TFTP directory prefix. */
212 char *pszTFTPPrefix;
213 /** Boot file name to provide in the DHCP server response. */
214 char *pszBootFile;
215 /** tftp server name to provide in the DHCP server response. */
216 char *pszNextServer;
217 /** Polling thread. */
218 PPDMTHREAD pSlirpThread;
219 /** Queue for NAT-thread-external events. */
220 RTREQQUEUE hSlirpReqQueue;
221 /** The guest IP for port-forwarding. */
222 uint32_t GuestIP;
223 /** Link state set when the VM is suspended. */
224 PDMNETWORKLINKSTATE enmLinkStateWant;
225
226#ifdef RT_OS_WINDOWS
227 /** Wakeup socket pair for NAT thread.
228 * Entry #0 is write, entry #1 is read. */
229 SOCKET ahWakeupSockPair[2];
230#else
231 /** The write end of the control pipe. */
232 RTPIPE hPipeWrite;
233 /** The read end of the control pipe. */
234 RTPIPE hPipeRead;
235#endif
236 /** count of unconsumed bytes sent to notify NAT thread */
237 volatile uint64_t cbWakeupNotifs;
238
239#define DRV_PROFILE_COUNTER(name, dsc) STAMPROFILE Stat ## name
240#define DRV_COUNTING_COUNTER(name, dsc) STAMCOUNTER Stat ## name
241#include "slirp/counters.h"
242 /** thread delivering packets for receiving by the guest */
243 PPDMTHREAD pRecvThread;
244 /** event to wakeup the guest receive thread */
245 RTSEMEVENT hEventRecv;
246 /** Receive Req queue (deliver packets to the guest) */
247 RTREQQUEUE hRecvReqQueue;
248
249 /** makes access to device func RecvAvail and Recv atomical. */
250 RTCRITSECT DevAccessLock;
251 /** Number of in-flight packets. */
252 volatile uint32_t cPkts;
253
254 /** Transmit lock taken by BeginXmit and released by EndXmit. */
255 RTCRITSECT XmitLock;
256
257#ifdef RT_OS_DARWIN
258 /* Handle of the DNS watcher runloop source. */
259 CFRunLoopSourceRef hRunLoopSrcDnsWatcher;
260#endif
261} DRVNAT;
262AssertCompileMemberAlignment(DRVNAT, StatNATRecvWakeups, 8);
263/** Pointer to the NAT driver instance data. */
264typedef DRVNAT *PDRVNAT;
265
266
267/*********************************************************************************************************************************
268* Internal Functions *
269*********************************************************************************************************************************/
270static void drvNATNotifyNATThread(PDRVNAT pThis, const char *pszWho);
271static int drvNATTimersAdjustTimeoutDown(PDRVNAT pThis, int cMsTimeout);
272static void drvNATTimersRunExpired(PDRVNAT pThis);
273static DECLCALLBACK(int) drvNAT_AddPollCb(int iFd, int iEvents, void *opaque);
274static DECLCALLBACK(int64_t) drvNAT_ClockGetNsCb(void *opaque);
275static DECLCALLBACK(int) drvNAT_GetREventsCb(int idx, void *opaque);
276static DECLCALLBACK(int) drvNATNotifyApplyPortForwardCommand(PDRVNAT pThis, bool fRemove, bool fUdp, const char *pszHostIp,
277 uint16_t u16HostPort, const char *pszGuestIp, uint16_t u16GuestPort);
278
279
280
281/*
282 * PDM Function Implementations
283 */
284
285/**
286 * @callback_method_impl{FNPDMTHREADDRV}
287 *
288 * Queues guest process received packet. Triggered by drvNATRecvWakeup.
289 */
290static DECLCALLBACK(int) drvNATRecv(PPDMDRVINS pDrvIns, PPDMTHREAD pThread)
291{
292 PDRVNAT pThis = PDMINS_2_DATA(pDrvIns, PDRVNAT);
293
294 if (pThread->enmState == PDMTHREADSTATE_INITIALIZING)
295 return VINF_SUCCESS;
296
297 while (pThread->enmState == PDMTHREADSTATE_RUNNING)
298 {
299 RTReqQueueProcess(pThis->hRecvReqQueue, 0);
300 if (ASMAtomicReadU32(&pThis->cPkts) == 0)
301 RTSemEventWait(pThis->hEventRecv, RT_INDEFINITE_WAIT);
302 }
303 return VINF_SUCCESS;
304}
305
306/**
307 * @callback_method_impl{FNPDMTHREADWAKEUPDRV}
308 */
309static DECLCALLBACK(int) drvNATRecvWakeup(PPDMDRVINS pDrvIns, PPDMTHREAD pThread)
310{
311 RT_NOREF(pThread);
312 PDRVNAT pThis = PDMINS_2_DATA(pDrvIns, PDRVNAT);
313 int rc = RTSemEventSignal(pThis->hEventRecv);
314
315 STAM_COUNTER_INC(&pThis->StatNATRecvWakeups);
316 return rc;
317}
318
319/**
320 * @brief Processes incoming packet (to guest).
321 *
322 * @param pThis Pointer to DRVNAT state for current context.
323 * @param pBuf Pointer to packet buffer.
324 * @param cb Size of packet in buffer.
325 *
326 * @thread NAT
327 */
328static DECLCALLBACK(void) drvNATRecvWorker(PDRVNAT pThis, void *pBuf, size_t cb)
329{
330 int rc;
331 STAM_PROFILE_START(&pThis->StatNATRecv, a);
332
333 rc = RTCritSectEnter(&pThis->DevAccessLock);
334 AssertRC(rc);
335
336 STAM_PROFILE_START(&pThis->StatNATRecvWait, b);
337 rc = pThis->pIAboveNet->pfnWaitReceiveAvail(pThis->pIAboveNet, RT_INDEFINITE_WAIT);
338 STAM_PROFILE_STOP(&pThis->StatNATRecvWait, b);
339
340 if (RT_SUCCESS(rc))
341 {
342 rc = pThis->pIAboveNet->pfnReceive(pThis->pIAboveNet, pBuf, cb);
343 AssertRC(rc);
344 RTMemFree(pBuf);
345 pBuf = NULL;
346 }
347 else if ( rc != VERR_TIMEOUT
348 && rc != VERR_INTERRUPTED)
349 {
350 AssertRC(rc);
351 }
352
353 rc = RTCritSectLeave(&pThis->DevAccessLock);
354 AssertRC(rc);
355 ASMAtomicDecU32(&pThis->cPkts);
356 drvNATNotifyNATThread(pThis, "drvNATRecvWorker");
357 STAM_PROFILE_STOP(&pThis->StatNATRecv, a);
358}
359
360/**
361 * Frees a S/G buffer allocated by drvNATNetworkUp_AllocBuf.
362 *
363 * @param pThis Pointer to the NAT instance.
364 * @param pSgBuf The S/G buffer to free.
365 *
366 * @thread NAT
367 */
368static void drvNATFreeSgBuf(PDRVNAT pThis, PPDMSCATTERGATHER pSgBuf)
369{
370 RT_NOREF(pThis);
371 Assert((pSgBuf->fFlags & PDMSCATTERGATHER_FLAGS_MAGIC_MASK) == PDMSCATTERGATHER_FLAGS_MAGIC);
372 pSgBuf->fFlags = 0;
373 if (pSgBuf->pvAllocator)
374 {
375 Assert(!pSgBuf->pvUser);
376 RTMemFree(pSgBuf->aSegs[0].pvSeg);
377 }
378 else if (pSgBuf->pvUser)
379 {
380 RTMemFree(pSgBuf->aSegs[0].pvSeg);
381 pSgBuf->aSegs[0].pvSeg = NULL;
382 RTMemFree(pSgBuf->pvUser);
383 pSgBuf->pvUser = NULL;
384 }
385 RTMemFree(pSgBuf);
386}
387
388/**
389 * Worker function for drvNATSend().
390 *
391 * @param pThis Pointer to the NAT instance.
392 * @param pSgBuf The scatter/gather buffer.
393 * @thread NAT
394 */
395static DECLCALLBACK(void) drvNATSendWorker(PDRVNAT pThis, PPDMSCATTERGATHER pSgBuf)
396{
397 LogFlowFunc(("pThis=%p pSgBuf=%p\n", pThis, pSgBuf));
398
399 if (pThis->enmLinkState == PDMNETWORKLINKSTATE_UP)
400 {
401 if (pSgBuf->pvAllocator)
402 {
403 /*
404 * A normal frame.
405 */
406 LogFlowFunc(("pvAllocator=%p LB %#zx\n", pSgBuf->pvAllocator, pSgBuf->cbUsed));
407 slirp_input(pThis->pNATState->pSlirp, (uint8_t const *)pSgBuf->pvAllocator, (int)pSgBuf->cbUsed);
408 }
409 else
410 {
411 /*
412 * Do segmentation offloading.
413 */
414 /* Do not attempt to segment frames with invalid GSO parameters. */
415 PCPDMNETWORKGSO pGso = (PCPDMNETWORKGSO)pSgBuf->pvUser;
416 if (PDMNetGsoIsValid(pGso, sizeof(*pGso), pSgBuf->cbUsed))
417 {
418 uint32_t const cSegs = PDMNetGsoCalcSegmentCount(pGso, pSgBuf->cbUsed);
419 Assert(cSegs > 1);
420 uint8_t * const pbSeg = (uint8_t *)RTMemAlloc(DRVNAT_MAXFRAMESIZE); /** @todo r=bird: we could use a stack buffer here... */
421 if (pbSeg)
422 {
423 uint8_t const * const pbFrame = (uint8_t const *)pSgBuf->aSegs[0].pvSeg;
424 LogFlowFunc(("GSO %p LB %#zx - creating %u segments out of it\n", pbFrame, pSgBuf->cbUsed, cSegs));
425 for (uint32_t iSeg = 0; iSeg < cSegs; iSeg++)
426 {
427 uint32_t cbPayload, cbHdrs;
428 uint32_t offPayload = PDMNetGsoCarveSegment(pGso, pbFrame, pSgBuf->cbUsed,
429 iSeg, cSegs, pbSeg, &cbHdrs, &cbPayload);
430 Assert(cbHdrs > 0);
431 Assert(cbHdrs < DRVNAT_MAXFRAMESIZE);
432 Assert(cbPayload > 0);
433 Assert(cbPayload < DRVNAT_MAXFRAMESIZE);
434 AssertBreak((uint64_t)cbHdrs + cbPayload <= DRVNAT_MAXFRAMESIZE);
435
436 memcpy(&pbSeg[cbHdrs], &pbFrame[offPayload], cbPayload);
437
438 slirp_input(pThis->pNATState->pSlirp, pbSeg, (int)(cbPayload + cbHdrs));
439 }
440 RTMemFree(pbSeg);
441 }
442 else
443 AssertFailed();
444 }
445 }
446 }
447
448 LogFlowFunc(("leave\n"));
449 drvNATFreeSgBuf(pThis, pSgBuf);
450}
451
452/**
453 * @interface_method_impl{PDMINETWORKUP,pfnBeginXmit}
454 */
455static DECLCALLBACK(int) drvNATNetworkUp_BeginXmit(PPDMINETWORKUP pInterface, bool fOnWorkerThread)
456{
457 RT_NOREF(fOnWorkerThread);
458 PDRVNAT pThis = RT_FROM_MEMBER(pInterface, DRVNAT, INetworkUp);
459 int rc = RTCritSectTryEnter(&pThis->XmitLock);
460 if (RT_FAILURE(rc))
461 {
462 /** @todo Kick the worker thread when we have one... */
463 rc = VERR_TRY_AGAIN;
464 }
465 LogFlowFunc(("Beginning xmit...\n"));
466 return rc;
467}
468
469/**
470 * @interface_method_impl{PDMINETWORKUP,pfnAllocBuf}
471 */
472static DECLCALLBACK(int) drvNATNetworkUp_AllocBuf(PPDMINETWORKUP pInterface, size_t cbMin,
473 PCPDMNETWORKGSO pGso, PPPDMSCATTERGATHER ppSgBuf)
474{
475 PDRVNAT pThis = RT_FROM_MEMBER(pInterface, DRVNAT, INetworkUp);
476 Assert(RTCritSectIsOwner(&pThis->XmitLock));
477
478 LogFlowFuncEnter();
479
480 /*
481 * Drop the incoming frame if the NAT thread isn't running.
482 */
483 if (pThis->pSlirpThread->enmState != PDMTHREADSTATE_RUNNING)
484 {
485 Log(("drvNATNetowrkUp_AllocBuf: returns VERR_NET_DOWN\n"));
486 return VERR_NET_DOWN;
487 }
488
489 /*
490 * Allocate a scatter/gather buffer and an mbuf.
491 */
492 PPDMSCATTERGATHER pSgBuf = (PPDMSCATTERGATHER)RTMemAllocZ(sizeof(PDMSCATTERGATHER));
493 if (!pSgBuf)
494 return VERR_NO_MEMORY;
495 if (!pGso)
496 {
497 /*
498 * Drop the frame if it is too big.
499 */
500 if (cbMin >= DRVNAT_MAXFRAMESIZE)
501 {
502 Log(("drvNATNetowrkUp_AllocBuf: drops over-sized frame (%u bytes), returns VERR_INVALID_PARAMETER\n",
503 cbMin));
504 RTMemFree(pSgBuf);
505 return VERR_INVALID_PARAMETER;
506 }
507
508 pSgBuf->pvUser = NULL;
509 pSgBuf->aSegs[0].cbSeg = RT_ALIGN_Z(cbMin, 128);
510 pSgBuf->aSegs[0].pvSeg = RTMemAlloc(pSgBuf->aSegs[0].cbSeg);
511 pSgBuf->pvAllocator = pSgBuf->aSegs[0].pvSeg;
512
513 if (!pSgBuf->pvAllocator)
514 {
515 RTMemFree(pSgBuf);
516 return VERR_TRY_AGAIN;
517 }
518 }
519 else
520 {
521 /*
522 * Drop the frame if its segment is too big.
523 */
524 if (pGso->cbHdrsTotal + pGso->cbMaxSeg >= DRVNAT_MAXFRAMESIZE)
525 {
526 Log(("drvNATNetowrkUp_AllocBuf: drops over-sized frame (%u bytes), returns VERR_INVALID_PARAMETER\n",
527 pGso->cbHdrsTotal + pGso->cbMaxSeg));
528 RTMemFree(pSgBuf);
529 return VERR_INVALID_PARAMETER;
530 }
531
532 pSgBuf->pvUser = RTMemDup(pGso, sizeof(*pGso));
533 pSgBuf->pvAllocator = NULL;
534
535 pSgBuf->aSegs[0].cbSeg = RT_ALIGN_Z(cbMin, 128);
536 pSgBuf->aSegs[0].pvSeg = RTMemAlloc(pSgBuf->aSegs[0].cbSeg);
537 if (!pSgBuf->pvUser || !pSgBuf->aSegs[0].pvSeg)
538 {
539 RTMemFree(pSgBuf->aSegs[0].pvSeg);
540 RTMemFree(pSgBuf->pvUser);
541 RTMemFree(pSgBuf);
542 return VERR_TRY_AGAIN;
543 }
544 }
545
546 /*
547 * Initialize the S/G buffer and return.
548 */
549 pSgBuf->fFlags = PDMSCATTERGATHER_FLAGS_MAGIC | PDMSCATTERGATHER_FLAGS_OWNER_1;
550 pSgBuf->cbUsed = 0;
551 pSgBuf->cbAvailable = pSgBuf->aSegs[0].cbSeg;
552 pSgBuf->cSegs = 1;
553
554 *ppSgBuf = pSgBuf;
555 return VINF_SUCCESS;
556}
557
558/**
559 * @interface_method_impl{PDMINETWORKUP,pfnFreeBuf}
560 */
561static DECLCALLBACK(int) drvNATNetworkUp_FreeBuf(PPDMINETWORKUP pInterface, PPDMSCATTERGATHER pSgBuf)
562{
563 PDRVNAT pThis = RT_FROM_MEMBER(pInterface, DRVNAT, INetworkUp);
564 Assert(RTCritSectIsOwner(&pThis->XmitLock));
565 drvNATFreeSgBuf(pThis, pSgBuf);
566 return VINF_SUCCESS;
567}
568
569/**
570 * @interface_method_impl{PDMINETWORKUP,pfnSendBuf}
571 */
572static DECLCALLBACK(int) drvNATNetworkUp_SendBuf(PPDMINETWORKUP pInterface, PPDMSCATTERGATHER pSgBuf, bool fOnWorkerThread)
573{
574 RT_NOREF(fOnWorkerThread);
575 PDRVNAT pThis = RT_FROM_MEMBER(pInterface, DRVNAT, INetworkUp);
576 Assert((pSgBuf->fFlags & PDMSCATTERGATHER_FLAGS_OWNER_MASK) == PDMSCATTERGATHER_FLAGS_OWNER_1);
577 Assert(RTCritSectIsOwner(&pThis->XmitLock));
578
579 LogFlowFunc(("enter\n"));
580
581 int rc;
582 if (pThis->pSlirpThread->enmState == PDMTHREADSTATE_RUNNING)
583 {
584 rc = RTReqQueueCallEx(pThis->hSlirpReqQueue, NULL /*ppReq*/, 0 /*cMillies*/, RTREQFLAGS_VOID | RTREQFLAGS_NO_WAIT,
585 (PFNRT)drvNATSendWorker, 2, pThis, pSgBuf);
586 if (RT_SUCCESS(rc))
587 {
588 drvNATNotifyNATThread(pThis, "drvNATNetworkUp_SendBuf");
589 LogFlowFunc(("leave success\n"));
590 return VINF_SUCCESS;
591 }
592
593 rc = VERR_NET_NO_BUFFER_SPACE;
594 }
595 else
596 rc = VERR_NET_DOWN;
597 drvNATFreeSgBuf(pThis, pSgBuf);
598 LogFlowFunc(("leave rc=%Rrc\n", rc));
599 return rc;
600}
601
602/**
603 * @interface_method_impl{PDMINETWORKUP,pfnEndXmit}
604 */
605static DECLCALLBACK(void) drvNATNetworkUp_EndXmit(PPDMINETWORKUP pInterface)
606{
607 PDRVNAT pThis = RT_FROM_MEMBER(pInterface, DRVNAT, INetworkUp);
608 RTCritSectLeave(&pThis->XmitLock);
609}
610
611/**
612 * Get the NAT thread out of poll/WSAWaitForMultipleEvents
613 */
614static void drvNATNotifyNATThread(PDRVNAT pThis, const char *pszWho)
615{
616 RT_NOREF(pszWho);
617#ifdef RT_OS_WINDOWS
618 int cbWritten = send(pThis->ahWakeupSockPair[0], "", 1, NULL);
619 if (RT_LIKELY(cbWritten != SOCKET_ERROR))
620 {
621 /* Count how many bites we send down the socket */
622 ASMAtomicIncU64(&pThis->cbWakeupNotifs);
623 }
624 else
625 Log4(("Notify NAT Thread Error %d\n", WSAGetLastError()));
626#else
627 /* kick poll() */
628 size_t cbIgnored;
629 int rc = RTPipeWrite(pThis->hPipeWrite, "", 1, &cbIgnored);
630 AssertRC(rc);
631 if (RT_SUCCESS(rc))
632 {
633 /* Count how many bites we send down the socket */
634 ASMAtomicIncU64(&pThis->cbWakeupNotifs);
635 }
636#endif
637}
638
639/**
640 * @interface_method_impl{PDMINETWORKUP,pfnSetPromiscuousMode}
641 */
642static DECLCALLBACK(void) drvNATNetworkUp_SetPromiscuousMode(PPDMINETWORKUP pInterface, bool fPromiscuous)
643{
644 RT_NOREF(pInterface, fPromiscuous);
645 LogFlow(("drvNATNetworkUp_SetPromiscuousMode: fPromiscuous=%d\n", fPromiscuous));
646 /* nothing to do */
647}
648
649/**
650 * Worker function for drvNATNetworkUp_NotifyLinkChanged().
651 * @thread "NAT" thread.
652 *
653 * @param pThis Pointer to DRVNAT state for current context.
654 * @param enmLinkState Enum value of link state.
655 *
656 * @thread NAT
657 */
658static DECLCALLBACK(void) drvNATNotifyLinkChangedWorker(PDRVNAT pThis, PDMNETWORKLINKSTATE enmLinkState)
659{
660 pThis->enmLinkState = pThis->enmLinkStateWant = enmLinkState;
661 switch (enmLinkState)
662 {
663 case PDMNETWORKLINKSTATE_UP:
664 LogRel(("NAT: Link up\n"));
665 break;
666
667 case PDMNETWORKLINKSTATE_DOWN:
668 case PDMNETWORKLINKSTATE_DOWN_RESUME:
669 LogRel(("NAT: Link down\n"));
670 break;
671
672 default:
673 AssertMsgFailed(("drvNATNetworkUp_NotifyLinkChanged: unexpected link state %d\n", enmLinkState));
674 }
675}
676
677/**
678 * Notification on link status changes.
679 *
680 * @param pInterface Pointer to the interface structure containing the called function pointer.
681 * @param enmLinkState The new link state.
682 *
683 * @thread EMT
684 */
685static DECLCALLBACK(void) drvNATNetworkUp_NotifyLinkChanged(PPDMINETWORKUP pInterface, PDMNETWORKLINKSTATE enmLinkState)
686{
687 PDRVNAT pThis = RT_FROM_MEMBER(pInterface, DRVNAT, INetworkUp);
688
689 LogFlow(("drvNATNetworkUp_NotifyLinkChanged: enmLinkState=%d\n", enmLinkState));
690
691 /* Don't queue new requests if the NAT thread is not running (e.g. paused,
692 * stopping), otherwise we would deadlock. Memorize the change. */
693 if (pThis->pSlirpThread->enmState != PDMTHREADSTATE_RUNNING)
694 {
695 pThis->enmLinkStateWant = enmLinkState;
696 return;
697 }
698
699 PRTREQ pReq;
700 int rc = RTReqQueueCallEx(pThis->hSlirpReqQueue, &pReq, 0 /*cMillies*/, RTREQFLAGS_VOID,
701 (PFNRT)drvNATNotifyLinkChangedWorker, 2, pThis, enmLinkState);
702 if (rc == VERR_TIMEOUT)
703 {
704 drvNATNotifyNATThread(pThis, "drvNATNetworkUp_NotifyLinkChanged");
705 rc = RTReqWait(pReq, RT_INDEFINITE_WAIT);
706 AssertRC(rc);
707 }
708 else
709 AssertRC(rc);
710 RTReqRelease(pReq);
711}
712
713/**
714 * NAT thread handling the slirp stuff.
715 *
716 * The slirp implementation is single-threaded so we execute this enginre in a
717 * dedicated thread. We take care that this thread does not become the
718 * bottleneck: If the guest wants to send, a request is enqueued into the
719 * hSlirpReqQueue and handled asynchronously by this thread. If this thread
720 * wants to deliver packets to the guest, it enqueues a request into
721 * hRecvReqQueue which is later handled by the Recv thread.
722 *
723 * @param pDrvIns Pointer to PDM driver context.
724 * @param pThread Pointer to calling thread context.
725 *
726 * @returns VBox status code
727 *
728 * @thread NAT
729 */
730static DECLCALLBACK(int) drvNATAsyncIoThread(PPDMDRVINS pDrvIns, PPDMTHREAD pThread)
731{
732 PDRVNAT pThis = PDMINS_2_DATA(pDrvIns, PDRVNAT);
733
734 /* The first polling entry is for the control/wakeup pipe. */
735 /** @todo r=bird: Either do this manually or use drvNAT_AddPollCb(), don't do
736 * both without a comment like HACK ALERT or something... (The causual
737 * reader would think drvNAT_AddPollCb has a different function than
738 * the code here.) */
739#ifdef RT_OS_WINDOWS
740 drvNAT_AddPollCb(pThis->ahWakeupSockPair[1], SLIRP_POLL_IN | SLIRP_POLL_HUP, pThis);
741 pThis->pNATState->polls[0].fd = pThis->ahWakeupSockPair[1];
742#else
743 unsigned int cPollNegRet = 0;
744 RTHCINTPTR const i64NativeReadPipe = RTPipeToNative(pThis->hPipeRead);
745 int const fdNativeReadPipe = (int)i64NativeReadPipe;
746 Assert(fdNativeReadPipe == i64NativeReadPipe); Assert(fdNativeReadPipe >= 0);
747 drvNAT_AddPollCb(fdNativeReadPipe, SLIRP_POLL_IN | SLIRP_POLL_HUP, pThis);
748 pThis->pNATState->polls[0].fd = fdNativeReadPipe;
749 pThis->pNATState->polls[0].events = POLLRDNORM | POLLPRI | POLLRDBAND;
750 pThis->pNATState->polls[0].revents = 0;
751#endif /* !RT_OS_WINDOWS */
752
753 LogFlow(("drvNATAsyncIoThread: pThis=%p\n", pThis));
754
755 if (pThread->enmState == PDMTHREADSTATE_INITIALIZING)
756 return VINF_SUCCESS;
757
758 if (pThis->enmLinkStateWant != pThis->enmLinkState)
759 drvNATNotifyLinkChangedWorker(pThis, pThis->enmLinkStateWant);
760
761 /*
762 * Polling loop.
763 */
764 while (pThread->enmState == PDMTHREADSTATE_RUNNING)
765 {
766 /*
767 * To prevent concurrent execution of sending/receiving threads
768 */
769 pThis->pNATState->nsock = 1;
770
771 int cMsTimeout = DRVNAT_DEFAULT_TIMEOUT;
772 slirp_pollfds_fill(pThis->pNATState->pSlirp, &cMsTimeout, drvNAT_AddPollCb /* SlirpAddPollCb */, pThis /* opaque */);
773 cMsTimeout = drvNATTimersAdjustTimeoutDown(pThis, cMsTimeout);
774
775#ifdef RT_OS_WINDOWS
776 int cChangedFDs = WSAPoll(pThis->pNATState->polls, pThis->pNATState->nsock, cMsTimeout);
777#else
778 int cChangedFDs = poll(pThis->pNATState->polls, pThis->pNATState->nsock, cMsTimeout);
779#endif
780 if (cChangedFDs < 0)
781 {
782#ifdef RT_OS_WINDOWS
783 int const iLastErr = WSAGetLastError(); /* (In debug builds LogRel translates to two RTLogLoggerExWeak calls.) */
784 LogRel(("NAT: RTWinPoll returned error=%Rrc (cChangedFDs=%d)\n", iLastErr, cChangedFDs));
785 Log4(("NAT: NSOCK = %d\n", pThis->pNATState->nsock));
786#else
787 if (errno == EINTR)
788 {
789 Log2(("NAT: signal was caught while sleep on poll\n"));
790 /* No error, just process all outstanding requests but don't wait */
791 cChangedFDs = 0;
792 }
793 else if (cPollNegRet++ > 128)
794 {
795 LogRel(("NAT: Poll returns (%s) suppressed %d\n", strerror(errno), cPollNegRet));
796 cPollNegRet = 0;
797 }
798#endif
799 }
800
801 Log4(("%s: poll\n", __FUNCTION__));
802 slirp_pollfds_poll(pThis->pNATState->pSlirp, cChangedFDs < 0, drvNAT_GetREventsCb, pThis /* opaque */);
803
804 /*
805 * Drain the control pipe if necessary.
806 *
807 * Note! drvNATSend decoupled so we don't know how many times
808 * device's thread sends before we've entered multiplex,
809 * so to avoid false alarm drain pipe here to the very end
810 */
811 /** @todo revise the above note. */
812 if (pThis->pNATState->polls[0].revents & (POLLRDNORM|POLLPRI|POLLRDBAND)) /* POLLPRI won't be seen with WSAPoll. */
813 {
814 char achBuf[1024];
815 size_t cbRead;
816 uint64_t cbWakeupNotifs = ASMAtomicReadU64(&pThis->cbWakeupNotifs);
817#ifdef RT_OS_WINDOWS
818 /** @todo r=bird: This returns -1 (SOCKET_ERROR) on failure, so any kind of
819 * error return here and we'll bugger up cbWakeupNotifs! */
820 cbRead = recv(pThis->ahWakeupSockPair[1], &achBuf[0], RT_MIN(cbWakeupNotifs, sizeof(achBuf)), NULL);
821#else
822 /** @todo r=bird: cbRead may in theory be used uninitialized here! This
823 * isn't blocking, though, so we won't get stuck here if we mess up
824 * the count. */
825 RTPipeRead(pThis->hPipeRead, &achBuf[0], RT_MIN(cbWakeupNotifs, sizeof(achBuf)), &cbRead);
826#endif
827 ASMAtomicSubU64(&pThis->cbWakeupNotifs, cbRead);
828 }
829
830 /* process _all_ outstanding requests but don't wait */
831 RTReqQueueProcess(pThis->hSlirpReqQueue, 0);
832 drvNATTimersRunExpired(pThis);
833 }
834
835 return VINF_SUCCESS;
836}
837
838/**
839 * Unblock the send thread so it can respond to a state change.
840 *
841 * @returns VBox status code.
842 * @param pDrvIns The pcnet device instance.
843 * @param pThread The send thread.
844 *
845 * @thread ?
846 */
847static DECLCALLBACK(int) drvNATAsyncIoWakeup(PPDMDRVINS pDrvIns, PPDMTHREAD pThread)
848{
849 RT_NOREF(pThread);
850 PDRVNAT pThis = PDMINS_2_DATA(pDrvIns, PDRVNAT);
851
852 drvNATNotifyNATThread(pThis, "drvNATAsyncIoWakeup");
853 return VINF_SUCCESS;
854}
855
856/**
857 * @interface_method_impl{PDMIBASE,pfnQueryInterface}
858 */
859static DECLCALLBACK(void *) drvNATQueryInterface(PPDMIBASE pInterface, const char *pszIID)
860{
861 PPDMDRVINS pDrvIns = PDMIBASE_2_PDMDRV(pInterface);
862 PDRVNAT pThis = PDMINS_2_DATA(pDrvIns, PDRVNAT);
863
864 PDMIBASE_RETURN_INTERFACE(pszIID, PDMIBASE, &pDrvIns->IBase);
865 PDMIBASE_RETURN_INTERFACE(pszIID, PDMINETWORKUP, &pThis->INetworkUp);
866 PDMIBASE_RETURN_INTERFACE(pszIID, PDMINETWORKNATCONFIG, &pThis->INetworkNATCfg);
867 return NULL;
868}
869
870/**
871 * Info handler.
872 *
873 * @param pDrvIns The PDM driver context.
874 * @param pHlp ....
875 * @param pszArgs Unused.
876 *
877 * @thread any
878 */
879static DECLCALLBACK(void) drvNATInfo(PPDMDRVINS pDrvIns, PCDBGFINFOHLP pHlp, const char *pszArgs)
880{
881 RT_NOREF(pszArgs);
882 PDRVNAT pThis = PDMINS_2_DATA(pDrvIns, PDRVNAT);
883 pHlp->pfnPrintf(pHlp, "libslirp Connection Info:\n");
884 pHlp->pfnPrintf(pHlp, slirp_connection_info(pThis->pNATState->pSlirp));
885 pHlp->pfnPrintf(pHlp, "libslirp Neighbor Info:\n");
886 pHlp->pfnPrintf(pHlp, slirp_neighbor_info(pThis->pNATState->pSlirp));
887 pHlp->pfnPrintf(pHlp, "libslirp Version String: %s \n", slirp_version_string());
888}
889
890/**
891 * Sets up the redirectors.
892 *
893 * @returns VBox status code.
894 * @param uInstance ?
895 * @param pThis ?
896 * @param pCfg The configuration handle.
897 * @param pNetwork Unused.
898 *
899 * @thread ?
900 */
901static int drvNATConstructRedir(unsigned iInstance, PDRVNAT pThis, PCFGMNODE pCfg, PRTNETADDRIPV4 pNetwork)
902{
903 /** @todo r=jack: rewrite to support IPv6? */
904 PPDMDRVINS pDrvIns = pThis->pDrvIns;
905 PCPDMDRVHLPR3 pHlp = pDrvIns->pHlpR3;
906
907 RT_NOREF(pNetwork); /** @todo figure why pNetwork isn't used */
908
909 PCFGMNODE pPFTree = pHlp->pfnCFGMGetChild(pCfg, "PortForwarding");
910 if (pPFTree == NULL)
911 return VINF_SUCCESS;
912
913 /*
914 * Enumerate redirections.
915 */
916 for (PCFGMNODE pNode = pHlp->pfnCFGMGetFirstChild(pPFTree); pNode; pNode = pHlp->pfnCFGMGetNextChild(pNode))
917 {
918 /*
919 * Validate the port forwarding config.
920 */
921 if (!pHlp->pfnCFGMAreValuesValid(pNode, "Name\0Protocol\0UDP\0HostPort\0GuestPort\0GuestIP\0BindIP\0"))
922 return PDMDRV_SET_ERROR(pDrvIns, VERR_PDM_DRVINS_UNKNOWN_CFG_VALUES,
923 N_("Unknown configuration in port forwarding"));
924
925 /* protocol type */
926 bool fUDP;
927 char szProtocol[32];
928 int rc;
929 GET_STRING(rc, pDrvIns, pNode, "Protocol", szProtocol[0], sizeof(szProtocol));
930 if (rc == VERR_CFGM_VALUE_NOT_FOUND)
931 {
932 fUDP = false;
933 GET_BOOL(rc, pDrvIns, pNode, "UDP", fUDP);
934 }
935 else if (RT_SUCCESS(rc))
936 {
937 if (!RTStrICmp(szProtocol, "TCP"))
938 fUDP = false;
939 else if (!RTStrICmp(szProtocol, "UDP"))
940 fUDP = true;
941 else
942 return PDMDrvHlpVMSetError(pDrvIns, VERR_INVALID_PARAMETER, RT_SRC_POS,
943 N_("NAT#%d: Invalid configuration value for \"Protocol\": \"%s\""),
944 iInstance, szProtocol);
945 }
946 else
947 return PDMDrvHlpVMSetError(pDrvIns, rc, RT_SRC_POS,
948 N_("NAT#%d: configuration query for \"Protocol\" failed"),
949 iInstance);
950 /* host port */
951 uint16_t iHostPort;
952 GET_U16_STRICT(rc, pDrvIns, pNode, "HostPort", iHostPort);
953
954 /* guest port */
955 uint16_t iGuestPort;
956 GET_U16_STRICT(rc, pDrvIns, pNode, "GuestPort", iGuestPort);
957
958 /** @todo r=jack: why are we using IP INADD_ANY for port forward when FE does not do so. */
959 /* host address ("BindIP" name is rather unfortunate given "HostPort" to go with it) */
960 char szHostIp[MAX_IP_ADDRESS_STR_LEN_W_NULL] = {0};
961 // GETIP_DEF(rc, pDrvIns, pNode, szHostIp, INADDR_ANY);
962 GET_STRING(rc, pDrvIns, pNode, "BindIP", szHostIp[0], sizeof(szHostIp));
963
964 /* guest address */
965 char szGuestIp[MAX_IP_ADDRESS_STR_LEN_W_NULL] = {0};
966 // GETIP_DEF(rc, pDrvIns, pNode, szGuestIp, INADDR_ANY);
967 GET_STRING(rc, pDrvIns, pNode, "GuestIP", szGuestIp[0], sizeof(szGuestIp));
968
969 LogRelMax(256, ("Preconfigured port forward rule discovered on startup: fUdp=%d, HostIp=%s, u16HostPort=%u, GuestIp=%s, u16GuestPort=%u\n",
970 RT_BOOL(fUDP), szHostIp, iHostPort, szGuestIp, iGuestPort));
971
972 /*
973 * Apply port forward.
974 */
975 if (drvNATNotifyApplyPortForwardCommand(pThis, false /* fRemove */, fUDP, szHostIp, iHostPort, szGuestIp, iGuestPort) < 0)
976 LogFlowFunc(("NAT#%d: configuration error: failed to set up redirection of %d to %d. "
977 "Probably a conflict with existing services or other rules",
978 iInstance, iHostPort, iGuestPort));
979 } /* for each redir rule */
980
981 return VINF_SUCCESS;
982}
983
984/**
985 * Applies port forwarding between guest and host.
986 *
987 * @param pThis Pointer to DRVNAT state for current context.
988 * @param fRemove Flag to remove port forward instead of create.
989 * @param fUdp Flag specifying if UDP. If false, TCP.
990 * @param pszHostIp String of host IP address.
991 * @param u16HostPort Host port to forward to.
992 * @param pszGuestIp String of guest IP address.
993 * @param u16GuestPort Guest port to forward.
994 *
995 * @thread ?
996 */
997static DECLCALLBACK(int) drvNATNotifyApplyPortForwardCommand(PDRVNAT pThis, bool fRemove, bool fUdp, const char *pszHostIp,
998 uint16_t u16HostPort, const char *pszGuestIp, uint16_t u16GuestPort)
999{
1000 /** @todo r=jack:
1001 * - rewrite for IPv6
1002 * - do we want to lock the guestIp to the VMs IP?
1003 */
1004 struct in_addr guestIp, hostIp;
1005
1006 if ( pszHostIp == NULL
1007 || inet_aton(pszHostIp, &hostIp) == 0)
1008 hostIp.s_addr = INADDR_ANY;
1009
1010 if ( pszGuestIp == NULL
1011 || inet_aton(pszGuestIp, &guestIp) == 0)
1012 guestIp.s_addr = pThis->GuestIP;
1013
1014 int rc;
1015 if (fRemove)
1016 rc = slirp_remove_hostfwd(pThis->pNATState->pSlirp, fUdp, hostIp, u16HostPort);
1017 else
1018 rc = slirp_add_hostfwd(pThis->pNATState->pSlirp, fUdp, hostIp,
1019 u16HostPort, guestIp, u16GuestPort);
1020 if (rc < 0)
1021 {
1022 LogRelFunc(("Port forward modify FAIL! Details: fRemove=%d, fUdp=%d, pszHostIp=%s, u16HostPort=%u, pszGuestIp=%s, u16GuestPort=%u\n",
1023 RT_BOOL(fRemove), RT_BOOL(fUdp), pszHostIp, u16HostPort, pszGuestIp, u16GuestPort));
1024 return PDMDrvHlpVMSetError(pThis->pDrvIns, VERR_NAT_REDIR_SETUP, RT_SRC_POS,
1025 N_("NAT#%d: configuration error: failed to set up redirection of %d to %d. "
1026 "Probably a conflict with existing services or other rules"),
1027 pThis->pDrvIns->iInstance, u16HostPort, u16GuestPort);
1028 }
1029
1030 return rc;
1031}
1032
1033/**
1034 * @interface_method_impl{PDMINETWORKNATCONFIG,pfnRedirectRuleCommand}
1035 */
1036static DECLCALLBACK(int) drvNATNetworkNatConfigRedirect(PPDMINETWORKNATCONFIG pInterface, bool fRemove,
1037 bool fUdp, const char *pHostIp, uint16_t u16HostPort,
1038 const char *pGuestIp, uint16_t u16GuestPort)
1039{
1040 LogRelMax(256, ("New port forwarded added: "
1041 "fRemove=%d, fUdp=%d, pHostIp=%s, u16HostPort=%u, pGuestIp=%s, u16GuestPort=%u\n",
1042 RT_BOOL(fRemove), RT_BOOL(fUdp), pHostIp, u16HostPort, pGuestIp, u16GuestPort));
1043 PDRVNAT pThis = RT_FROM_MEMBER(pInterface, DRVNAT, INetworkNATCfg);
1044 /* Execute the command directly if the VM is not running. */
1045 int rc;
1046 if (pThis->pSlirpThread->enmState != PDMTHREADSTATE_RUNNING)
1047 rc = drvNATNotifyApplyPortForwardCommand(pThis, fRemove, fUdp, pHostIp, u16HostPort, pGuestIp,u16GuestPort);
1048 else
1049 {
1050 PRTREQ pReq;
1051 rc = RTReqQueueCallEx(pThis->hSlirpReqQueue, &pReq, 0 /*cMillies*/, RTREQFLAGS_VOID,
1052 (PFNRT)drvNATNotifyApplyPortForwardCommand, 7,
1053 pThis, fRemove, fUdp, pHostIp, u16HostPort, pGuestIp, u16GuestPort);
1054 if (rc == VERR_TIMEOUT)
1055 {
1056 drvNATNotifyNATThread(pThis, "drvNATNetworkNatConfigRedirect");
1057 rc = RTReqWait(pReq, RT_INDEFINITE_WAIT);
1058 AssertRC(rc);
1059 }
1060 else
1061 AssertRC(rc);
1062
1063 RTReqRelease(pReq);
1064 }
1065 return rc;
1066}
1067
1068/**
1069 * @interface_method_impl{PDMINETWORKNATCONFIG,pfnNotifyDnsChanged}
1070 */
1071static DECLCALLBACK(void) drvNATNotifyDnsChanged(PPDMINETWORKNATCONFIG pInterface, PCPDMINETWORKNATDNSCONFIG pDnsConf)
1072{
1073 PDRVNAT const pThis = RT_FROM_MEMBER(pInterface, DRVNAT, INetworkNATCfg);
1074 SlirpState * const pNATState = pThis->pNATState;
1075 AssertReturnVoid(pNATState);
1076 AssertReturnVoid(pNATState->pSlirp);
1077
1078 if (!pNATState->fPassDomain)
1079 return;
1080
1081 LogRel(("NAT: DNS settings changed, triggering update\n"));
1082
1083 if (pDnsConf->szDomainName[0] == '\0')
1084 slirp_set_vdomainname(pNATState->pSlirp, NULL);
1085 else
1086 slirp_set_vdomainname(pNATState->pSlirp, pDnsConf->szDomainName);
1087
1088 slirp_set_vdnssearch(pNATState->pSlirp, pDnsConf->papszSearchDomains);
1089 /** @todo Convert the papszNameServers entries to IP address and tell about
1090 * the first IPv4 and IPv6 ones. */
1091}
1092
1093
1094/*
1095 * Libslirp Utility Functions
1096 */
1097
1098/**
1099 * Reduce the given timeout to match the earliest timer deadline.
1100 *
1101 * @returns Updated cMsTimeout value.
1102 * @param pThis Pointer to NAT State context.
1103 * @param cMsTimeout The timeout to adjust, in milliseconds.
1104 *
1105 * @thread pSlirpThread
1106 */
1107static int drvNATTimersAdjustTimeoutDown(PDRVNAT pThis, int cMsTimeout)
1108{
1109 /** @todo r=bird: This and a most other stuff would be easier if msExpire was
1110 * unsigned and we used UINT64_MAX for stopped timers. */
1111 /** @todo The timer code isn't thread safe, it assumes a single user thread
1112 * (pSlirpThread). */
1113
1114 /* Find the first (lowest) deadline. */
1115 int64_t msDeadline = INT64_MAX;
1116 for (SlirpTimer *pCurrent = pThis->pNATState->pTimerHead; pCurrent; pCurrent = pCurrent->next)
1117 if (pCurrent->msExpire < msDeadline && pCurrent->msExpire > 0)
1118 msDeadline = pCurrent->msExpire;
1119
1120 /* Adjust the timeout if there is a timer with a deadline. */
1121 if (msDeadline < INT64_MAX)
1122 {
1123 int64_t const msNow = drvNAT_ClockGetNsCb(pThis) / RT_NS_1MS;
1124 if (msNow < msDeadline)
1125 {
1126 int64_t cMilliesToDeadline = msDeadline - msNow;
1127 if (cMilliesToDeadline < cMsTimeout)
1128 cMsTimeout = (int)cMilliesToDeadline;
1129 }
1130 else
1131 cMsTimeout = 0;
1132 }
1133
1134 return cMsTimeout;
1135}
1136
1137/**
1138 * Run expired timers.
1139 *
1140 * @param opaque Pointer to NAT State context.
1141 *
1142 * @thread pSlirpThread
1143 */
1144static void drvNATTimersRunExpired(PDRVNAT pThis)
1145{
1146 int64_t const msNow = drvNAT_ClockGetNsCb(pThis) / RT_NS_1MS;
1147 SlirpTimer *pCurrent = pThis->pNATState->pTimerHead;
1148 while (pCurrent != NULL)
1149 {
1150 SlirpTimer * const pNext = pCurrent->next; /* (in case the timer is destroyed from the callback) */
1151 if (pCurrent->msExpire <= msNow && pCurrent->msExpire > 0)
1152 {
1153 pCurrent->msExpire = 0;
1154 pCurrent->pHandler(pCurrent->opaque);
1155 }
1156 pCurrent = pNext;
1157 }
1158}
1159
1160/**
1161 * Converts slirp representation of poll events to host representation.
1162 *
1163 * @param iEvents Integer representing slirp type poll events.
1164 *
1165 * @returns Integer representing host type poll events.
1166 */
1167static short drvNAT_PollEventSlirpToHost(int iEvents)
1168{
1169 short iRet = 0;
1170#ifndef RT_OS_WINDOWS
1171 if (iEvents & SLIRP_POLL_IN) iRet |= POLLIN;
1172 if (iEvents & SLIRP_POLL_OUT) iRet |= POLLOUT;
1173 if (iEvents & SLIRP_POLL_PRI) iRet |= POLLPRI;
1174 if (iEvents & SLIRP_POLL_ERR) iRet |= POLLERR;
1175 if (iEvents & SLIRP_POLL_HUP) iRet |= POLLHUP;
1176#else
1177 if (iEvents & SLIRP_POLL_IN) iRet |= (POLLRDNORM | POLLRDBAND);
1178 if (iEvents & SLIRP_POLL_OUT) iRet |= POLLWRNORM;
1179 if (iEvents & SLIRP_POLL_PRI) iRet |= (POLLIN);
1180 if (iEvents & SLIRP_POLL_ERR) iRet |= 0;
1181 if (iEvents & SLIRP_POLL_HUP) iRet |= 0;
1182#endif
1183 return iRet;
1184}
1185
1186/**
1187 * Converts host representation of poll events to slirp representation.
1188 *
1189 * @param iEvents Integer representing host type poll events.
1190 *
1191 * @returns Integer representing slirp type poll events.
1192 *
1193 * @thread ?
1194 */
1195static int drvNAT_PollEventHostToSlirp(int iEvents) {
1196 int iRet = 0;
1197#ifndef RT_OS_WINDOWS
1198 if (iEvents & POLLIN) iRet |= SLIRP_POLL_IN;
1199 if (iEvents & POLLOUT) iRet |= SLIRP_POLL_OUT;
1200 if (iEvents & POLLPRI) iRet |= SLIRP_POLL_PRI;
1201 if (iEvents & POLLERR) iRet |= SLIRP_POLL_ERR;
1202 if (iEvents & POLLHUP) iRet |= SLIRP_POLL_HUP;
1203#else
1204 if (iEvents & (POLLRDNORM | POLLRDBAND)) iRet |= SLIRP_POLL_IN;
1205 if (iEvents & POLLWRNORM) iRet |= SLIRP_POLL_OUT;
1206 if (iEvents & (POLLPRI)) iRet |= SLIRP_POLL_PRI;
1207 if (iEvents & POLLERR) iRet |= SLIRP_POLL_ERR;
1208 if (iEvents & POLLHUP) iRet |= SLIRP_POLL_HUP;
1209#endif
1210 return iRet;
1211}
1212
1213
1214/*
1215 * Libslirp Callbacks
1216 */
1217/** @todo r=bird: None of these require DECLCALLBACK as such, since the libslirp
1218 * structure they're used with doesn't use DECLCALLBACKMEMBER or similar. */
1219/**
1220 * Callback called by libslirp to send packet into guest.
1221 *
1222 * @param pvBuf Pointer to packet buffer.
1223 * @param cb Size of packet.
1224 * @param pvUser Pointer to NAT State context.
1225 *
1226 * @returns Size of packet received or -1 on error.
1227 *
1228 * @thread ?
1229 */
1230static DECLCALLBACK(ssize_t) drvNAT_SendPacketCb(const void *pvBuf, ssize_t cb, void *pvUser /* PDRVNAT */)
1231{
1232 PDRVNAT const pThis = (PDRVNAT)pvUser;
1233 Assert(pThis);
1234
1235 void * const pvNewBuf = RTMemDup(pvBuf, cb);
1236 AssertReturn(pvNewBuf, -1);
1237
1238 LogFlow(("slirp_output BEGIN %p %d\n", pvNewBuf, cb));
1239 Log6(("slirp_output: pvNewBuf=%p cb=%#x (pThis=%p)\n"
1240 "%.*Rhxd\n", pvNewBuf, cb, pThis, cb, pvNewBuf));
1241
1242 /* don't queue new requests when the NAT thread is about to stop */
1243 if (pThis->pSlirpThread->enmState != PDMTHREADSTATE_RUNNING)
1244 return -1;
1245
1246 ASMAtomicIncU32(&pThis->cPkts);
1247 int rc = RTReqQueueCallEx(pThis->hRecvReqQueue, NULL /*ppReq*/, 0 /*cMillies*/, RTREQFLAGS_VOID | RTREQFLAGS_NO_WAIT,
1248 (PFNRT)drvNATRecvWorker, 3, pThis, pvNewBuf, cb);
1249 AssertRCStmt(rc, RTMemFree(pvNewBuf));
1250 drvNATRecvWakeup(pThis->pDrvIns, pThis->pRecvThread);
1251
1252 /** @todo r=bird: explain why we wake up the other thread here? */
1253 drvNATNotifyNATThread(pThis, "drvNAT_SendPacketCb");
1254
1255 STAM_COUNTER_INC(&pThis->StatQueuePktSent);
1256 LogFlowFuncLeave();
1257 return cb;
1258}
1259
1260/**
1261 * Callback called by libslirp when the guest does something wrong.
1262 *
1263 * @param pMsg Error message string.
1264 * @param pvUser Pointer to NAT State context.
1265 *
1266 * @thread ?
1267 */
1268static DECLCALLBACK(void) drvNAT_GuestErrorCb(const char *pszMsg, void *pvUser)
1269{
1270 /* Note! This is _just_ libslirp complaining about odd guest behaviour.
1271 It is nothing we need to create popup messages in the GUI about. */
1272 LogRelMax(250, ("NAT Guest Error: %s\n", pszMsg));
1273 RT_NOREF(pvUser);
1274}
1275
1276/**
1277 * Callback called by libslirp to get the current timestamp in nanoseconds.
1278 *
1279 * @param pvUser Pointer to NAT State context.
1280 *
1281 * @returns 64-bit signed integer representing time in nanoseconds.
1282 */
1283static DECLCALLBACK(int64_t) drvNAT_ClockGetNsCb(void *pvUser)
1284{
1285 RT_NOREF(pvUser);
1286 return (int64_t)RTTimeNanoTS();
1287}
1288
1289/**
1290 * Callback called by slirp to create a new timer and insert it into the given list.
1291 *
1292 * @param slirpTimeCb Callback function supplied to the new timer upon timer expiry.
1293 * Called later by the timeout handler.
1294 * @param cb_opaque Opaque object supplied to slirpTimeCb when called. Should be
1295 * Identical to the opaque parameter.
1296 * @param opaque Pointer to NAT State context.
1297 *
1298 * @returns Pointer to new timer.
1299 */
1300static DECLCALLBACK(void *) drvNAT_TimerNewCb(SlirpTimerCb slirpTimeCb, void *cb_opaque, void *opaque)
1301{
1302 PDRVNAT pThis = (PDRVNAT)opaque;
1303 Assert(pThis);
1304
1305 SlirpTimer * const pNewTimer = (SlirpTimer *)RTMemAlloc(sizeof(SlirpTimer));
1306 if (pNewTimer)
1307 {
1308 pNewTimer->msExpire = 0;
1309 pNewTimer->pHandler = slirpTimeCb;
1310 pNewTimer->opaque = cb_opaque;
1311 /** @todo r=bird: Not thread safe. Assumes pSlirpThread */
1312 pNewTimer->next = pThis->pNATState->pTimerHead;
1313 pThis->pNATState->pTimerHead = pNewTimer;
1314 }
1315 return pNewTimer;
1316}
1317
1318/**
1319 * Callback called by slirp to free a timer.
1320 *
1321 * @param pvTimer Pointer to slirpTimer object to be freed.
1322 * @param pvUser Pointer to NAT State context.
1323 */
1324static DECLCALLBACK(void) drvNAT_TimerFreeCb(void *pvTimer, void *pvUser)
1325{
1326 PDRVNAT const pThis = (PDRVNAT)pvUser;
1327 SlirpTimer * const pTimer = (SlirpTimer *)pvTimer;
1328 Assert(pThis);
1329 /** @todo r=bird: Not thread safe. Assumes pSlirpThread */
1330
1331 SlirpTimer *pPrev = NULL;
1332 SlirpTimer *pCurrent = pThis->pNATState->pTimerHead;
1333 while (pCurrent != NULL)
1334 {
1335 if (pCurrent == pTimer)
1336 {
1337 /* unlink it. */
1338 if (!pPrev)
1339 pThis->pNATState->pTimerHead = pCurrent->next;
1340 else
1341 pPrev->next = pCurrent->next;
1342 pCurrent->next = NULL;
1343 RTMemFree(pCurrent);
1344 return;
1345 }
1346
1347 /* advance */
1348 pPrev = pCurrent;
1349 pCurrent = pCurrent->next;
1350 }
1351 Assert(!pTimer);
1352}
1353
1354/**
1355 * Callback called by slirp to modify a timer.
1356 *
1357 * @param pvTimer Pointer to slirpTimer object to be modified.
1358 * @param msNewDeadlineTs The new absolute expiration time in milliseconds.
1359 * Zero stops it.
1360 * @param pvUser Pointer to NAT State context.
1361 */
1362static DECLCALLBACK(void) drvNAT_TimerModCb(void *pvTimer, int64_t msNewDeadlineTs, void *pvUser)
1363{
1364 SlirpTimer * const pTimer = (SlirpTimer *)pvTimer;
1365 /** @todo r=bird: ASSUMES pSlirpThread, otherwise it may need to be woken up! */
1366 pTimer->msExpire = msNewDeadlineTs;
1367 RT_NOREF(pvUser);
1368}
1369
1370/**
1371 * Callback called by slirp when there is I/O that needs to happen.
1372 *
1373 * @param opaque Pointer to NAT State context.
1374 */
1375static DECLCALLBACK(void) drvNAT_NotifyCb(void *opaque)
1376{
1377 PDRVNAT pThis = (PDRVNAT)opaque;
1378 drvNATNotifyNATThread(pThis, "drvNAT_NotifyCb");
1379}
1380
1381/**
1382 * Registers poll. Unused function (other than logging).
1383 */
1384static DECLCALLBACK(void) drvNAT_RegisterPoll(int fd, void *opaque)
1385{
1386 RT_NOREF(fd, opaque);
1387 Log4(("Poll registered: fd=%d\n", fd));
1388}
1389
1390/**
1391 * Unregisters poll. Unused function (other than logging).
1392 */
1393static DECLCALLBACK(void) drvNAT_UnregisterPoll(int fd, void *opaque)
1394{
1395 RT_NOREF(fd, opaque);
1396 Log4(("Poll unregistered: fd=%d\n", fd));
1397}
1398
1399/**
1400 * Callback function to add entry to pollfd array.
1401 *
1402 * @param iFd Integer of system file descriptor of socket.
1403 * (on windows, this is a VBox internal, not system, value).
1404 * @param iEvents Integer of slirp type poll events.
1405 * @param opaque Pointer to NAT State context.
1406 *
1407 * @returns Index of latest pollfd entry.
1408 *
1409 * @thread ?
1410 */
1411static DECLCALLBACK(int) drvNAT_AddPollCb(int iFd, int iEvents, void *opaque)
1412{
1413 PDRVNAT pThis = (PDRVNAT)opaque;
1414
1415 if (pThis->pNATState->nsock + 1 >= pThis->pNATState->uPollCap)
1416 {
1417 size_t cbNew = pThis->pNATState->uPollCap * 2 * sizeof(struct pollfd);
1418 struct pollfd *pvNew = (struct pollfd *)RTMemRealloc(pThis->pNATState->polls, cbNew);
1419 if (pvNew)
1420 {
1421 pThis->pNATState->polls = pvNew;
1422 pThis->pNATState->uPollCap *= 2;
1423 }
1424 else
1425 return -1;
1426 }
1427
1428 unsigned int uIdx = pThis->pNATState->nsock;
1429 Assert(uIdx < INT_MAX);
1430#ifdef RT_OS_WINDOWS
1431 pThis->pNATState->polls[uIdx].fd = libslirp_wrap_RTHandleTableLookup(iFd);
1432#else
1433 pThis->pNATState->polls[uIdx].fd = iFd;
1434#endif
1435 pThis->pNATState->polls[uIdx].events = drvNAT_PollEventSlirpToHost(iEvents);
1436 pThis->pNATState->polls[uIdx].revents = 0;
1437 pThis->pNATState->nsock += 1;
1438 return uIdx;
1439}
1440
1441/**
1442 * Get translated revents from a poll at a given index.
1443 *
1444 * @param idx Integer index of poll.
1445 * @param opaque Pointer to NAT State context.
1446 *
1447 * @returns Integer representing transalted revents.
1448 *
1449 * @thread ?
1450 */
1451static DECLCALLBACK(int) drvNAT_GetREventsCb(int idx, void *opaque)
1452{
1453 PDRVNAT pThis = (PDRVNAT)opaque;
1454 struct pollfd* polls = pThis->pNATState->polls;
1455 return drvNAT_PollEventHostToSlirp(polls[idx].revents);
1456}
1457
1458/**
1459 * Contructor/Destructor
1460 */
1461/**
1462 * Destruct a driver instance.
1463 *
1464 * Most VM resources are freed by the VM. This callback is provided so that any non-VM
1465 * resources can be freed correctly.
1466 *
1467 * @param pDrvIns The driver instance data.
1468 */
1469static DECLCALLBACK(void) drvNATDestruct(PPDMDRVINS pDrvIns)
1470{
1471 PDRVNAT pThis = PDMINS_2_DATA(pDrvIns, PDRVNAT);
1472 LogFlow(("drvNATDestruct:\n"));
1473 PDMDRV_CHECK_VERSIONS_RETURN_VOID(pDrvIns);
1474
1475 SlirpState * const pNATState = pThis->pNATState;
1476 if (pNATState)
1477 {
1478 if (pNATState->pSlirp)
1479 {
1480 slirp_cleanup(pNATState->pSlirp);
1481 pNATState->pSlirp = NULL;
1482 }
1483
1484#ifdef VBOX_WITH_STATISTICS
1485# define DRV_PROFILE_COUNTER(name, dsc) DEREGISTER_COUNTER(name, pThis)
1486# define DRV_COUNTING_COUNTER(name, dsc) DEREGISTER_COUNTER(name, pThis)
1487# include "slirp/counters.h"
1488#endif
1489 RTMemFree(pNATState->polls);
1490 pNATState->polls = NULL;
1491
1492 RTMemFree(pNATState);
1493 pThis->pNATState = NULL;
1494 }
1495
1496 RTReqQueueDestroy(pThis->hSlirpReqQueue);
1497 pThis->hSlirpReqQueue = NIL_RTREQQUEUE;
1498
1499 RTReqQueueDestroy(pThis->hRecvReqQueue);
1500 pThis->hRecvReqQueue = NIL_RTREQQUEUE;
1501
1502 RTSemEventDestroy(pThis->hEventRecv);
1503 pThis->hEventRecv = NIL_RTSEMEVENT;
1504
1505 if (RTCritSectIsInitialized(&pThis->DevAccessLock))
1506 RTCritSectDelete(&pThis->DevAccessLock);
1507
1508 if (RTCritSectIsInitialized(&pThis->XmitLock))
1509 RTCritSectDelete(&pThis->XmitLock);
1510
1511#ifndef RT_OS_WINDOWS
1512 RTPipeClose(pThis->hPipeRead);
1513 RTPipeClose(pThis->hPipeWrite);
1514 pThis->hPipeRead = NIL_RTPIPE;
1515 pThis->hPipeWrite = NIL_RTPIPE;
1516#endif
1517}
1518
1519/**
1520 * Construct a NAT network transport driver instance.
1521 *
1522 * @copydoc FNPDMDRVCONSTRUCT
1523 */
1524static DECLCALLBACK(int) drvNATConstruct(PPDMDRVINS pDrvIns, PCFGMNODE pCfg, uint32_t fFlags)
1525{
1526 RT_NOREF(fFlags);
1527 PDMDRV_CHECK_VERSIONS_RETURN(pDrvIns);
1528 PDRVNAT pThis = PDMINS_2_DATA(pDrvIns, PDRVNAT);
1529
1530 /*
1531 * Init the static parts.
1532 */
1533 pThis->pDrvIns = pDrvIns;
1534 pThis->hSlirpReqQueue = NIL_RTREQQUEUE;
1535 pThis->hEventRecv = NIL_RTSEMEVENT;
1536 pThis->hRecvReqQueue = NIL_RTREQQUEUE;
1537#ifndef RT_OS_WINDOWS
1538 pThis->hPipeRead = NIL_RTPIPE;
1539 pThis->hPipeWrite = NIL_RTPIPE;
1540#endif
1541
1542 SlirpState * const pNATState = (SlirpState *)RTMemAllocZ(sizeof(*pNATState));
1543 if (pNATState == NULL)
1544 return VERR_NO_MEMORY;
1545 pThis->pNATState = pNATState;
1546 pNATState->nsock = 0;
1547 pNATState->pTimerHead = NULL;
1548 pNATState->polls = (struct pollfd *)RTMemAllocZ(64 * sizeof(struct pollfd));
1549 AssertReturn(pNATState->polls, VERR_NO_MEMORY);
1550 pNATState->uPollCap = 64;
1551
1552 /* IBase */
1553 pDrvIns->IBase.pfnQueryInterface = drvNATQueryInterface;
1554
1555 /* INetwork */
1556 pThis->INetworkUp.pfnBeginXmit = drvNATNetworkUp_BeginXmit;
1557 pThis->INetworkUp.pfnAllocBuf = drvNATNetworkUp_AllocBuf;
1558 pThis->INetworkUp.pfnFreeBuf = drvNATNetworkUp_FreeBuf;
1559 pThis->INetworkUp.pfnSendBuf = drvNATNetworkUp_SendBuf;
1560 pThis->INetworkUp.pfnEndXmit = drvNATNetworkUp_EndXmit;
1561 pThis->INetworkUp.pfnSetPromiscuousMode = drvNATNetworkUp_SetPromiscuousMode;
1562 pThis->INetworkUp.pfnNotifyLinkChanged = drvNATNetworkUp_NotifyLinkChanged;
1563
1564 /* NAT engine configuration */
1565 pThis->INetworkNATCfg.pfnRedirectRuleCommand = drvNATNetworkNatConfigRedirect;
1566 pThis->INetworkNATCfg.pfnNotifyDnsChanged = drvNATNotifyDnsChanged;
1567
1568 /*
1569 * Validate the config.
1570 */
1571 PDMDRV_VALIDATE_CONFIG_RETURN(pDrvIns,
1572 "PassDomain"
1573 "|TFTPPrefix"
1574 "|BootFile"
1575 "|Network"
1576 "|NextServer"
1577 "|DNSProxy"
1578 "|BindIP"
1579 "|UseHostResolver"
1580 "|SlirpMTU"
1581 "|AliasMode"
1582 "|SockRcv"
1583 "|SockSnd"
1584 "|TcpRcv"
1585 "|TcpSnd"
1586 "|ICMPCacheLimit"
1587 "|SoMaxConnection"
1588 "|LocalhostReachable"
1589 "|HostResolverMappings"
1590 "|ForwardBroadcast"
1591 , "PortForwarding");
1592
1593 LogRel(("NAT: These CFGM parameters are currently not supported when using NAT:\n"
1594 " DNSProxy\n"
1595 " UseHostResolver\n"
1596 " AliasMode\n"
1597 " SockRcv\n"
1598 " SockSnd\n"
1599 " TcpRcv\n"
1600 " TcpSnd\n"
1601 " ICMPCacheLimit\n"
1602 " HostResolverMappings\n"
1603 ));
1604
1605 /*
1606 * Get the configuration settings.
1607 */
1608 int rc;
1609 /** @todo clean up the macros used here. S32 != int. Use defaults. ++ */
1610
1611 bool fPassDomain = true;
1612 GET_BOOL(rc, pDrvIns, pCfg, "PassDomain", fPassDomain);
1613 pNATState->fPassDomain = fPassDomain;
1614
1615 bool fForwardBroadcast = false;
1616 GET_BOOL(rc, pDrvIns, pCfg, "ForwardBroadcast", fForwardBroadcast);
1617
1618 GET_STRING_ALLOC(rc, pDrvIns, pCfg, "TFTPPrefix", pThis->pszTFTPPrefix);
1619 GET_STRING_ALLOC(rc, pDrvIns, pCfg, "BootFile", pThis->pszBootFile);
1620 GET_STRING_ALLOC(rc, pDrvIns, pCfg, "NextServer", pThis->pszNextServer);
1621
1622 int fDNSProxy = 0;
1623 GET_S32(rc, pDrvIns, pCfg, "DNSProxy", fDNSProxy);
1624 unsigned int MTU = 1500;
1625 GET_U32(rc, pDrvIns, pCfg, "SlirpMTU", MTU);
1626 int iIcmpCacheLimit = 100;
1627 GET_S32(rc, pDrvIns, pCfg, "ICMPCacheLimit", iIcmpCacheLimit);
1628 bool fLocalhostReachable = false;
1629 GET_BOOL(rc, pDrvIns, pCfg, "LocalhostReachable", fLocalhostReachable);
1630 int i32SoMaxConn = 10;
1631 GET_S32(rc, pDrvIns, pCfg, "SoMaxConnection", i32SoMaxConn);
1632
1633 /*
1634 * Query the network port interface.
1635 */
1636 pThis->pIAboveNet = PDMIBASE_QUERY_INTERFACE(pDrvIns->pUpBase, PDMINETWORKDOWN);
1637 if (!pThis->pIAboveNet)
1638 return PDMDRV_SET_ERROR(pDrvIns, VERR_PDM_MISSING_INTERFACE_ABOVE,
1639 N_("Configuration error: the above device/driver didn't export the network port interface"));
1640 pThis->pIAboveConfig = PDMIBASE_QUERY_INTERFACE(pDrvIns->pUpBase, PDMINETWORKCONFIG);
1641 if (!pThis->pIAboveConfig)
1642 return PDMDRV_SET_ERROR(pDrvIns, VERR_PDM_MISSING_INTERFACE_ABOVE,
1643 N_("Configuration error: the above device/driver didn't export the network config interface"));
1644
1645 /* Generate a network address for this network card. */
1646 char szNetwork[32]; /* xxx.xxx.xxx.xxx/yy */
1647 GET_STRING(rc, pDrvIns, pCfg, "Network", szNetwork[0], sizeof(szNetwork));
1648 if (rc == VERR_CFGM_VALUE_NOT_FOUND)
1649 return PDMDrvHlpVMSetError(pDrvIns, rc, RT_SRC_POS, N_("NAT%d: Configuration error: missing network"),
1650 pDrvIns->iInstance);
1651
1652 RTNETADDRIPV4 Network, Netmask;
1653 rc = RTCidrStrToIPv4(szNetwork, &Network, &Netmask);
1654 if (RT_FAILURE(rc))
1655 return PDMDrvHlpVMSetError(pDrvIns, rc, RT_SRC_POS,
1656 N_("NAT#%d: Configuration error: network '%s' describes not a valid IPv4 network"),
1657 pDrvIns->iInstance, szNetwork);
1658
1659 /*
1660 * Construct Libslirp Config.
1661 */
1662 LogFlow(("Here is what is coming out of the vbox config (NAT#%d):\n"
1663 " Network: %RTnaipv4\n"
1664 " Netmask: %RTnaipv4\n",
1665 pDrvIns->iInstance, RT_H2BE_U32(Network.u), RT_H2BE_U32(Netmask.u)));
1666
1667 /* IPv4: */
1668 struct in_addr vnetwork = RTNetIPv4AddrHEToInAddr(&Network);
1669 struct in_addr vnetmask = RTNetIPv4AddrHEToInAddr(&Netmask);
1670
1671 RTNETADDRIPV4 NetTemp = Network;
1672 NetTemp.u |= 2; /* Usually 10.0.2.2 */
1673 struct in_addr vhost = RTNetIPv4AddrHEToInAddr(&NetTemp);
1674
1675 NetTemp = Network;
1676 NetTemp.u |= 15; /* Usually 10.0.2.15 */
1677 struct in_addr vdhcp_start = RTNetIPv4AddrHEToInAddr(&NetTemp);
1678
1679 NetTemp = Network;
1680 NetTemp.u |= 3; /* Usually 10.0.2.3 */
1681 struct in_addr vnameserver = RTNetIPv4AddrHEToInAddr(&NetTemp);
1682
1683 SlirpConfig slirpCfg = { 0 };
1684 static SlirpCb slirpCallbacks = { 0 };
1685
1686 slirpCfg.version = 4;
1687 slirpCfg.restricted = false;
1688 slirpCfg.in_enabled = true;
1689 slirpCfg.vnetwork = vnetwork;
1690 slirpCfg.vnetmask = vnetmask;
1691 slirpCfg.vhost = vhost;
1692 slirpCfg.in6_enabled = true;
1693
1694 /* IPv6: Use the same prefix as the NAT Network default:
1695 [fd17:625c:f037:XXXX::/64] - RFC 4193 (ULA) Locally Assigned
1696 Global ID where XXXX, 16 bit Subnet ID, are two bytes from the
1697 middle of the IPv4 address, e.g. :0002: for 10.0.2.1. */
1698 inet_pton(AF_INET6, "fd17:625c:f037:0::", &slirpCfg.vprefix_addr6);
1699 inet_pton(AF_INET6, "fd17:625c:f037:0::2", &slirpCfg.vhost6);
1700 inet_pton(AF_INET6, "fd17:625c:f037:0::3", &slirpCfg.vnameserver6);
1701 slirpCfg.vprefix_len = 64;
1702
1703 /* Copy the middle of the IPv4 addresses to the IPv6 addresses. */
1704 slirpCfg.vprefix_addr6.s6_addr[6] = RT_BYTE2(vhost.s_addr);
1705 slirpCfg.vprefix_addr6.s6_addr[7] = RT_BYTE3(vhost.s_addr);
1706 slirpCfg.vhost6.s6_addr[6] = RT_BYTE2(vhost.s_addr);
1707 slirpCfg.vhost6.s6_addr[7] = RT_BYTE3(vhost.s_addr);
1708 slirpCfg.vnameserver6.s6_addr[6] = RT_BYTE2(vnameserver.s_addr);
1709 slirpCfg.vnameserver6.s6_addr[7] = RT_BYTE3(vnameserver.s_addr);
1710
1711 slirpCfg.vhostname = "vbox";
1712 slirpCfg.tftp_server_name = pThis->pszNextServer;
1713 slirpCfg.tftp_path = pThis->pszTFTPPrefix;
1714 slirpCfg.bootfile = pThis->pszBootFile;
1715 slirpCfg.vdhcp_start = vdhcp_start;
1716 slirpCfg.vnameserver = vnameserver;
1717 slirpCfg.if_mtu = MTU;
1718
1719 slirpCfg.vdnssearch = NULL;
1720 slirpCfg.vdomainname = NULL;
1721 slirpCfg.disable_host_loopback = !fLocalhostReachable;
1722 slirpCfg.fForwardBroadcast = fForwardBroadcast;
1723 slirpCfg.iSoMaxConn = i32SoMaxConn;
1724
1725 slirpCallbacks.send_packet = drvNAT_SendPacketCb;
1726 slirpCallbacks.guest_error = drvNAT_GuestErrorCb;
1727 slirpCallbacks.clock_get_ns = drvNAT_ClockGetNsCb;
1728 slirpCallbacks.timer_new = drvNAT_TimerNewCb;
1729 slirpCallbacks.timer_free = drvNAT_TimerFreeCb;
1730 slirpCallbacks.timer_mod = drvNAT_TimerModCb;
1731 slirpCallbacks.register_poll_fd = drvNAT_RegisterPoll;
1732 slirpCallbacks.unregister_poll_fd = drvNAT_UnregisterPoll;
1733 slirpCallbacks.notify = drvNAT_NotifyCb;
1734 slirpCallbacks.init_completed = NULL;
1735 slirpCallbacks.timer_new_opaque = NULL;
1736
1737 /*
1738 * Initialize Slirp
1739 */
1740 Slirp * const pSlirp = slirp_new(/* cfg */ &slirpCfg, /* callbacks */ &slirpCallbacks, /* opaque */ pThis);
1741 if (!pSlirp)
1742 return PDMDRV_SET_ERROR(pDrvIns, VERR_INTERNAL_ERROR_4,
1743 N_("Configuration error: libslirp failed to create new instance - probably misconfiguration"));
1744
1745 pNATState->pSlirp = pSlirp;
1746
1747 rc = drvNATConstructRedir(pDrvIns->iInstance, pThis, pCfg, &Network);
1748 AssertLogRelRCReturn(rc, rc);
1749
1750 rc = PDMDrvHlpSSMRegisterLoadDone(pDrvIns, NULL);
1751 AssertLogRelRCReturn(rc, rc);
1752
1753 rc = RTReqQueueCreate(&pThis->hSlirpReqQueue);
1754 AssertLogRelRCReturn(rc, rc);
1755
1756 rc = RTReqQueueCreate(&pThis->hRecvReqQueue);
1757 AssertLogRelRCReturn(rc, rc);
1758
1759 rc = PDMDrvHlpThreadCreate(pDrvIns, &pThis->pRecvThread, pThis, drvNATRecv,
1760 drvNATRecvWakeup, 256 * _1K, RTTHREADTYPE_IO, "NATRX");
1761 AssertRCReturn(rc, rc);
1762
1763 rc = RTSemEventCreate(&pThis->hEventRecv);
1764 AssertRCReturn(rc, rc);
1765
1766 rc = RTCritSectInit(&pThis->DevAccessLock);
1767 AssertRCReturn(rc, rc);
1768
1769 rc = RTCritSectInit(&pThis->XmitLock);
1770 AssertRCReturn(rc, rc);
1771
1772 char szTmp[128];
1773 RTStrPrintf(szTmp, sizeof(szTmp), "nat%d", pDrvIns->iInstance);
1774 PDMDrvHlpDBGFInfoRegister(pDrvIns, szTmp, "NAT info.", drvNATInfo);
1775
1776#ifdef VBOX_WITH_STATISTICS
1777# define DRV_PROFILE_COUNTER(name, dsc) REGISTER_COUNTER(name, pThis, STAMTYPE_PROFILE, STAMUNIT_TICKS_PER_CALL, dsc)
1778# define DRV_COUNTING_COUNTER(name, dsc) REGISTER_COUNTER(name, pThis, STAMTYPE_COUNTER, STAMUNIT_COUNT, dsc)
1779# include "slirp/counters.h"
1780#endif
1781
1782#ifdef RT_OS_WINDOWS
1783 /* Create the wakeup socket pair (idx=0 is write, idx=1 is read). */
1784 pThis->ahWakeupSockPair[0] = INVALID_SOCKET;
1785 pThis->ahWakeupSockPair[1] = INVALID_SOCKET;
1786 rc = RTWinSocketPair(AF_INET, SOCK_DGRAM, 0, pThis->ahWakeupSockPair);
1787 AssertRCReturn(rc, rc);
1788#else
1789 /* Create the control pipe. */
1790 rc = RTPipeCreate(&pThis->hPipeRead, &pThis->hPipeWrite, 0 /*fFlags*/);
1791 AssertRCReturn(rc, rc);
1792#endif
1793 /* initalize the notifier counter */
1794 pThis->cbWakeupNotifs = 0;
1795
1796 rc = PDMDrvHlpThreadCreate(pDrvIns, &pThis->pSlirpThread, pThis, drvNATAsyncIoThread,
1797 drvNATAsyncIoWakeup, 256 * _1K, RTTHREADTYPE_IO, "NAT");
1798 AssertRCReturn(rc, rc);
1799
1800 pThis->enmLinkState = pThis->enmLinkStateWant = PDMNETWORKLINKSTATE_UP;
1801
1802 return rc;
1803}
1804
1805/**
1806 * NAT network transport driver registration record.
1807 */
1808const PDMDRVREG g_DrvNATlibslirp =
1809{
1810 /* u32Version */
1811 PDM_DRVREG_VERSION,
1812 /* szName */
1813 "NAT",
1814 /* szRCMod */
1815 "",
1816 /* szR0Mod */
1817 "",
1818 /* pszDescription */
1819 "NATlibslrip Network Transport Driver",
1820 /* fFlags */
1821 PDM_DRVREG_FLAGS_HOST_BITS_DEFAULT,
1822 /* fClass. */
1823 PDM_DRVREG_CLASS_NETWORK,
1824 /* cMaxInstances */
1825 ~0U,
1826 /* cbInstance */
1827 sizeof(DRVNAT),
1828 /* pfnConstruct */
1829 drvNATConstruct,
1830 /* pfnDestruct */
1831 drvNATDestruct,
1832 /* pfnRelocate */
1833 NULL,
1834 /* pfnIOCtl */
1835 NULL,
1836 /* pfnPowerOn */
1837 NULL,
1838 /* pfnReset */
1839 NULL,
1840 /* pfnSuspend */
1841 NULL,
1842 /* pfnResume */
1843 NULL,
1844 /* pfnAttach */
1845 NULL,
1846 /* pfnDetach */
1847 NULL,
1848 /* pfnPowerOff */
1849 NULL,
1850 /* pfnSoftReset */
1851 NULL,
1852 /* u32EndVersion */
1853 PDM_DRVREG_VERSION
1854};
注意: 瀏覽 TracBrowser 來幫助您使用儲存庫瀏覽器

© 2025 Oracle Support Privacy / Do Not Sell My Info Terms of Use Trademark Policy Automated Access Etiquette