VirtualBox

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

Last change on this file since 108825 was 108820, checked in by vboxsync, 5 weeks ago

NAT/libslirp: fixed assert/order bug. bugref:10268

  • Property svn:eol-style set to native
  • Property svn:keywords set to Author Date Id Revision
File size: 65.9 KB
Line 
1/* $Id: DrvNATlibslirp.cpp 108820 2025-04-01 22:39:09Z 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.virtualbox.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
742 /* HACK ALERT: while Windows socket handling is weird, do this explicitly. */
743 pThis->pNATState->polls[0].fd = pThis->ahWakeupSockPair[1];
744#else
745 unsigned int cPollNegRet = 0;
746 RTHCINTPTR const i64NativeReadPipe = RTPipeToNative(pThis->hPipeRead);
747 int const fdNativeReadPipe = (int)i64NativeReadPipe;
748 Assert(fdNativeReadPipe == i64NativeReadPipe); Assert(fdNativeReadPipe >= 0);
749 drvNAT_AddPollCb(fdNativeReadPipe, SLIRP_POLL_IN | SLIRP_POLL_HUP, pThis);
750 pThis->pNATState->polls[0].fd = fdNativeReadPipe;
751 pThis->pNATState->polls[0].events = POLLRDNORM | POLLPRI | POLLRDBAND;
752 pThis->pNATState->polls[0].revents = 0;
753#endif /* !RT_OS_WINDOWS */
754
755 LogFlow(("drvNATAsyncIoThread: pThis=%p\n", pThis));
756
757 if (pThread->enmState == PDMTHREADSTATE_INITIALIZING)
758 return VINF_SUCCESS;
759
760 if (pThis->enmLinkStateWant != pThis->enmLinkState)
761 drvNATNotifyLinkChangedWorker(pThis, pThis->enmLinkStateWant);
762
763 /*
764 * Polling loop.
765 */
766 while (pThread->enmState == PDMTHREADSTATE_RUNNING)
767 {
768 /*
769 * To prevent concurrent execution of sending/receiving threads
770 */
771 pThis->pNATState->nsock = 1;
772
773 int cMsTimeout = DRVNAT_DEFAULT_TIMEOUT;
774 slirp_pollfds_fill(pThis->pNATState->pSlirp, &cMsTimeout, drvNAT_AddPollCb /* SlirpAddPollCb */, pThis /* opaque */);
775 cMsTimeout = drvNATTimersAdjustTimeoutDown(pThis, cMsTimeout);
776
777#ifdef RT_OS_WINDOWS
778 int cChangedFDs = WSAPoll(pThis->pNATState->polls, pThis->pNATState->nsock, cMsTimeout);
779#else
780 int cChangedFDs = poll(pThis->pNATState->polls, pThis->pNATState->nsock, cMsTimeout);
781#endif
782 if (cChangedFDs < 0)
783 {
784#ifdef RT_OS_WINDOWS
785 int const iLastErr = WSAGetLastError(); /* (In debug builds LogRel translates to two RTLogLoggerExWeak calls.) */
786 LogRel(("NAT: RTWinPoll returned error=%Rrc (cChangedFDs=%d)\n", iLastErr, cChangedFDs));
787 Log4(("NAT: NSOCK = %d\n", pThis->pNATState->nsock));
788#else
789 if (errno == EINTR)
790 {
791 Log2(("NAT: signal was caught while sleep on poll\n"));
792 /* No error, just process all outstanding requests but don't wait */
793 cChangedFDs = 0;
794 }
795 else if (cPollNegRet++ > 128)
796 {
797 LogRel(("NAT: Poll returns (%s) suppressed %d\n", strerror(errno), cPollNegRet));
798 cPollNegRet = 0;
799 }
800#endif
801 }
802
803 Log4(("%s: poll\n", __FUNCTION__));
804 slirp_pollfds_poll(pThis->pNATState->pSlirp, cChangedFDs < 0, drvNAT_GetREventsCb, pThis /* opaque */);
805
806 /*
807 * Drain the control pipe if necessary.
808 *
809 * Note! drvNATSend decoupled so we don't know how many times
810 * device's thread sends before we've entered multiplex,
811 * so to avoid false alarm drain pipe here to the very end
812 */
813 /** @todo revise the above note. */
814 if (pThis->pNATState->polls[0].revents & (POLLRDNORM|POLLPRI|POLLRDBAND)) /* POLLPRI won't be seen with WSAPoll. */
815 {
816 char achBuf[1024];
817 size_t cbRead;
818 uint64_t cbWakeupNotifs = ASMAtomicReadU64(&pThis->cbWakeupNotifs);
819#ifdef RT_OS_WINDOWS
820 /** @todo r=bird: This returns -1 (SOCKET_ERROR) on failure, so any kind of
821 * error return here and we'll bugger up cbWakeupNotifs! */
822 cbRead = recv(pThis->ahWakeupSockPair[1], &achBuf[0], RT_MIN(cbWakeupNotifs, sizeof(achBuf)), NULL);
823#else
824 /** @todo r=bird: cbRead may in theory be used uninitialized here! This
825 * isn't blocking, though, so we won't get stuck here if we mess up
826 * the count. */
827 RTPipeRead(pThis->hPipeRead, &achBuf[0], RT_MIN(cbWakeupNotifs, sizeof(achBuf)), &cbRead);
828#endif
829 ASMAtomicSubU64(&pThis->cbWakeupNotifs, cbRead);
830 }
831
832 /* process _all_ outstanding requests but don't wait */
833 RTReqQueueProcess(pThis->hSlirpReqQueue, 0);
834 drvNATTimersRunExpired(pThis);
835 }
836
837 return VINF_SUCCESS;
838}
839
840/**
841 * Unblock the send thread so it can respond to a state change.
842 *
843 * @returns VBox status code.
844 * @param pDrvIns The pcnet device instance.
845 * @param pThread The send thread.
846 *
847 * @thread ?
848 */
849static DECLCALLBACK(int) drvNATAsyncIoWakeup(PPDMDRVINS pDrvIns, PPDMTHREAD pThread)
850{
851 RT_NOREF(pThread);
852 PDRVNAT pThis = PDMINS_2_DATA(pDrvIns, PDRVNAT);
853
854 drvNATNotifyNATThread(pThis, "drvNATAsyncIoWakeup");
855 return VINF_SUCCESS;
856}
857
858/**
859 * @interface_method_impl{PDMIBASE,pfnQueryInterface}
860 */
861static DECLCALLBACK(void *) drvNATQueryInterface(PPDMIBASE pInterface, const char *pszIID)
862{
863 PPDMDRVINS pDrvIns = PDMIBASE_2_PDMDRV(pInterface);
864 PDRVNAT pThis = PDMINS_2_DATA(pDrvIns, PDRVNAT);
865
866 PDMIBASE_RETURN_INTERFACE(pszIID, PDMIBASE, &pDrvIns->IBase);
867 PDMIBASE_RETURN_INTERFACE(pszIID, PDMINETWORKUP, &pThis->INetworkUp);
868 PDMIBASE_RETURN_INTERFACE(pszIID, PDMINETWORKNATCONFIG, &pThis->INetworkNATCfg);
869 return NULL;
870}
871
872/**
873 * Info handler.
874 *
875 * @param pDrvIns The PDM driver context.
876 * @param pHlp ....
877 * @param pszArgs Unused.
878 *
879 * @thread any
880 */
881static DECLCALLBACK(void) drvNATInfo(PPDMDRVINS pDrvIns, PCDBGFINFOHLP pHlp, const char *pszArgs)
882{
883 RT_NOREF(pszArgs);
884 PDRVNAT pThis = PDMINS_2_DATA(pDrvIns, PDRVNAT);
885 pHlp->pfnPrintf(pHlp, "libslirp Connection Info:\n");
886 pHlp->pfnPrintf(pHlp, slirp_connection_info(pThis->pNATState->pSlirp));
887 pHlp->pfnPrintf(pHlp, "libslirp Neighbor Info:\n");
888 pHlp->pfnPrintf(pHlp, slirp_neighbor_info(pThis->pNATState->pSlirp));
889 pHlp->pfnPrintf(pHlp, "libslirp Version String: %s \n", slirp_version_string());
890}
891
892/**
893 * Sets up the redirectors.
894 *
895 * @returns VBox status code.
896 * @param uInstance ?
897 * @param pThis ?
898 * @param pCfg The configuration handle.
899 * @param pNetwork Unused.
900 *
901 * @thread ?
902 */
903static int drvNATConstructRedir(unsigned iInstance, PDRVNAT pThis, PCFGMNODE pCfg, PRTNETADDRIPV4 pNetwork)
904{
905 /** @todo r=jack: rewrite to support IPv6? */
906 PPDMDRVINS pDrvIns = pThis->pDrvIns;
907 PCPDMDRVHLPR3 pHlp = pDrvIns->pHlpR3;
908
909 RT_NOREF(pNetwork); /** @todo figure why pNetwork isn't used */
910
911 PCFGMNODE pPFTree = pHlp->pfnCFGMGetChild(pCfg, "PortForwarding");
912 if (pPFTree == NULL)
913 return VINF_SUCCESS;
914
915 /*
916 * Enumerate redirections.
917 */
918 for (PCFGMNODE pNode = pHlp->pfnCFGMGetFirstChild(pPFTree); pNode; pNode = pHlp->pfnCFGMGetNextChild(pNode))
919 {
920 /*
921 * Validate the port forwarding config.
922 */
923 if (!pHlp->pfnCFGMAreValuesValid(pNode, "Name\0Protocol\0UDP\0HostPort\0GuestPort\0GuestIP\0BindIP\0"))
924 return PDMDRV_SET_ERROR(pDrvIns, VERR_PDM_DRVINS_UNKNOWN_CFG_VALUES,
925 N_("Unknown configuration in port forwarding"));
926
927 /* protocol type */
928 bool fUDP;
929 char szProtocol[32];
930 int rc;
931 GET_STRING(rc, pDrvIns, pNode, "Protocol", szProtocol[0], sizeof(szProtocol));
932 if (rc == VERR_CFGM_VALUE_NOT_FOUND)
933 {
934 fUDP = false;
935 GET_BOOL(rc, pDrvIns, pNode, "UDP", fUDP);
936 }
937 else if (RT_SUCCESS(rc))
938 {
939 if (!RTStrICmp(szProtocol, "TCP"))
940 fUDP = false;
941 else if (!RTStrICmp(szProtocol, "UDP"))
942 fUDP = true;
943 else
944 return PDMDrvHlpVMSetError(pDrvIns, VERR_INVALID_PARAMETER, RT_SRC_POS,
945 N_("NAT#%d: Invalid configuration value for \"Protocol\": \"%s\""),
946 iInstance, szProtocol);
947 }
948 else
949 return PDMDrvHlpVMSetError(pDrvIns, rc, RT_SRC_POS,
950 N_("NAT#%d: configuration query for \"Protocol\" failed"),
951 iInstance);
952 /* host port */
953 uint16_t iHostPort;
954 GET_U16_STRICT(rc, pDrvIns, pNode, "HostPort", iHostPort);
955
956 /* guest port */
957 uint16_t iGuestPort;
958 GET_U16_STRICT(rc, pDrvIns, pNode, "GuestPort", iGuestPort);
959
960 /** @todo r=jack: why are we using IP INADD_ANY for port forward when FE does not do so. */
961 /* host address ("BindIP" name is rather unfortunate given "HostPort" to go with it) */
962 char szHostIp[MAX_IP_ADDRESS_STR_LEN_W_NULL] = {0};
963 // GETIP_DEF(rc, pDrvIns, pNode, szHostIp, INADDR_ANY);
964 GET_STRING(rc, pDrvIns, pNode, "BindIP", szHostIp[0], sizeof(szHostIp));
965
966 /* guest address */
967 char szGuestIp[MAX_IP_ADDRESS_STR_LEN_W_NULL] = {0};
968 // GETIP_DEF(rc, pDrvIns, pNode, szGuestIp, INADDR_ANY);
969 GET_STRING(rc, pDrvIns, pNode, "GuestIP", szGuestIp[0], sizeof(szGuestIp));
970
971 LogRelMax(256, ("Preconfigured port forward rule discovered on startup: fUdp=%d, HostIp=%s, u16HostPort=%u, GuestIp=%s, u16GuestPort=%u\n",
972 RT_BOOL(fUDP), szHostIp, iHostPort, szGuestIp, iGuestPort));
973
974 /*
975 * Apply port forward.
976 */
977 if (drvNATNotifyApplyPortForwardCommand(pThis, false /* fRemove */, fUDP, szHostIp, iHostPort, szGuestIp, iGuestPort) < 0)
978 LogFlowFunc(("NAT#%d: configuration error: failed to set up redirection of %d to %d. "
979 "Probably a conflict with existing services or other rules",
980 iInstance, iHostPort, iGuestPort));
981 } /* for each redir rule */
982
983 return VINF_SUCCESS;
984}
985
986/**
987 * Applies port forwarding between guest and host.
988 *
989 * @param pThis Pointer to DRVNAT state for current context.
990 * @param fRemove Flag to remove port forward instead of create.
991 * @param fUdp Flag specifying if UDP. If false, TCP.
992 * @param pszHostIp String of host IP address.
993 * @param u16HostPort Host port to forward to.
994 * @param pszGuestIp String of guest IP address.
995 * @param u16GuestPort Guest port to forward.
996 *
997 * @thread ?
998 */
999static DECLCALLBACK(int) drvNATNotifyApplyPortForwardCommand(PDRVNAT pThis, bool fRemove, bool fUdp, const char *pszHostIp,
1000 uint16_t u16HostPort, const char *pszGuestIp, uint16_t u16GuestPort)
1001{
1002 /** @todo r=jack:
1003 * - rewrite for IPv6
1004 * - do we want to lock the guestIp to the VMs IP?
1005 */
1006 struct in_addr guestIp, hostIp;
1007
1008 if ( pszHostIp == NULL
1009 || inet_aton(pszHostIp, &hostIp) == 0)
1010 hostIp.s_addr = INADDR_ANY;
1011
1012 if ( pszGuestIp == NULL
1013 || inet_aton(pszGuestIp, &guestIp) == 0)
1014 guestIp.s_addr = pThis->GuestIP;
1015
1016 int rc;
1017 if (fRemove)
1018 rc = slirp_remove_hostfwd(pThis->pNATState->pSlirp, fUdp, hostIp, u16HostPort);
1019 else
1020 rc = slirp_add_hostfwd(pThis->pNATState->pSlirp, fUdp, hostIp,
1021 u16HostPort, guestIp, u16GuestPort);
1022 if (rc < 0)
1023 {
1024 LogRelFunc(("Port forward modify FAIL! Details: fRemove=%d, fUdp=%d, pszHostIp=%s, u16HostPort=%u, pszGuestIp=%s, u16GuestPort=%u\n",
1025 RT_BOOL(fRemove), RT_BOOL(fUdp), pszHostIp, u16HostPort, pszGuestIp, u16GuestPort));
1026 return PDMDrvHlpVMSetError(pThis->pDrvIns, VERR_NAT_REDIR_SETUP, RT_SRC_POS,
1027 N_("NAT#%d: configuration error: failed to set up redirection of %d to %d. "
1028 "Probably a conflict with existing services or other rules"),
1029 pThis->pDrvIns->iInstance, u16HostPort, u16GuestPort);
1030 }
1031
1032 return rc;
1033}
1034
1035/**
1036 * @interface_method_impl{PDMINETWORKNATCONFIG,pfnRedirectRuleCommand}
1037 */
1038static DECLCALLBACK(int) drvNATNetworkNatConfigRedirect(PPDMINETWORKNATCONFIG pInterface, bool fRemove,
1039 bool fUdp, const char *pHostIp, uint16_t u16HostPort,
1040 const char *pGuestIp, uint16_t u16GuestPort)
1041{
1042 LogRelMax(256, ("New port forwarded added: "
1043 "fRemove=%d, fUdp=%d, pHostIp=%s, u16HostPort=%u, pGuestIp=%s, u16GuestPort=%u\n",
1044 RT_BOOL(fRemove), RT_BOOL(fUdp), pHostIp, u16HostPort, pGuestIp, u16GuestPort));
1045 PDRVNAT pThis = RT_FROM_MEMBER(pInterface, DRVNAT, INetworkNATCfg);
1046 /* Execute the command directly if the VM is not running. */
1047 int rc;
1048 if (pThis->pSlirpThread->enmState != PDMTHREADSTATE_RUNNING)
1049 rc = drvNATNotifyApplyPortForwardCommand(pThis, fRemove, fUdp, pHostIp, u16HostPort, pGuestIp,u16GuestPort);
1050 else
1051 {
1052 PRTREQ pReq;
1053 rc = RTReqQueueCallEx(pThis->hSlirpReqQueue, &pReq, 0 /*cMillies*/, RTREQFLAGS_VOID,
1054 (PFNRT)drvNATNotifyApplyPortForwardCommand, 7,
1055 pThis, fRemove, fUdp, pHostIp, u16HostPort, pGuestIp, u16GuestPort);
1056 if (rc == VERR_TIMEOUT)
1057 {
1058 drvNATNotifyNATThread(pThis, "drvNATNetworkNatConfigRedirect");
1059 rc = RTReqWait(pReq, RT_INDEFINITE_WAIT);
1060 AssertRC(rc);
1061 }
1062 else
1063 AssertRC(rc);
1064
1065 RTReqRelease(pReq);
1066 }
1067 return rc;
1068}
1069
1070/**
1071 * @interface_method_impl{PDMINETWORKNATCONFIG,pfnNotifyDnsChanged}
1072 */
1073static DECLCALLBACK(void) drvNATNotifyDnsChanged(PPDMINETWORKNATCONFIG pInterface, PCPDMINETWORKNATDNSCONFIG pDnsConf)
1074{
1075 PDRVNAT const pThis = RT_FROM_MEMBER(pInterface, DRVNAT, INetworkNATCfg);
1076 SlirpState * const pNATState = pThis->pNATState;
1077 AssertReturnVoid(pNATState);
1078 AssertReturnVoid(pNATState->pSlirp);
1079
1080 if (!pNATState->fPassDomain)
1081 return;
1082
1083 LogRel(("NAT: DNS settings changed, triggering update\n"));
1084
1085 if (pDnsConf->szDomainName[0] == '\0')
1086 slirp_set_vdomainname(pNATState->pSlirp, NULL);
1087 else
1088 slirp_set_vdomainname(pNATState->pSlirp, pDnsConf->szDomainName);
1089
1090 slirp_set_vdnssearch(pNATState->pSlirp, pDnsConf->papszSearchDomains);
1091 /** @todo Convert the papszNameServers entries to IP address and tell about
1092 * the first IPv4 and IPv6 ones. */
1093}
1094
1095
1096/*
1097 * Libslirp Utility Functions
1098 */
1099
1100/**
1101 * Reduce the given timeout to match the earliest timer deadline.
1102 *
1103 * @returns Updated cMsTimeout value.
1104 * @param pThis Pointer to NAT State context.
1105 * @param cMsTimeout The timeout to adjust, in milliseconds.
1106 *
1107 * @thread pSlirpThread
1108 */
1109static int drvNATTimersAdjustTimeoutDown(PDRVNAT pThis, int cMsTimeout)
1110{
1111 /** @todo r=bird: This and a most other stuff would be easier if msExpire was
1112 * unsigned and we used UINT64_MAX for stopped timers. */
1113 /** @todo The timer code isn't thread safe, it assumes a single user thread
1114 * (pSlirpThread). */
1115
1116 /* Find the first (lowest) deadline. */
1117 int64_t msDeadline = INT64_MAX;
1118 for (SlirpTimer *pCurrent = pThis->pNATState->pTimerHead; pCurrent; pCurrent = pCurrent->next)
1119 if (pCurrent->msExpire < msDeadline && pCurrent->msExpire > 0)
1120 msDeadline = pCurrent->msExpire;
1121
1122 /* Adjust the timeout if there is a timer with a deadline. */
1123 if (msDeadline < INT64_MAX)
1124 {
1125 int64_t const msNow = drvNAT_ClockGetNsCb(pThis) / RT_NS_1MS;
1126 if (msNow < msDeadline)
1127 {
1128 int64_t cMilliesToDeadline = msDeadline - msNow;
1129 if (cMilliesToDeadline < cMsTimeout)
1130 cMsTimeout = (int)cMilliesToDeadline;
1131 }
1132 else
1133 cMsTimeout = 0;
1134 }
1135
1136 return cMsTimeout;
1137}
1138
1139/**
1140 * Run expired timers.
1141 *
1142 * @param opaque Pointer to NAT State context.
1143 *
1144 * @thread pSlirpThread
1145 */
1146static void drvNATTimersRunExpired(PDRVNAT pThis)
1147{
1148 int64_t const msNow = drvNAT_ClockGetNsCb(pThis) / RT_NS_1MS;
1149 SlirpTimer *pCurrent = pThis->pNATState->pTimerHead;
1150 while (pCurrent != NULL)
1151 {
1152 SlirpTimer * const pNext = pCurrent->next; /* (in case the timer is destroyed from the callback) */
1153 if (pCurrent->msExpire <= msNow && pCurrent->msExpire > 0)
1154 {
1155 pCurrent->msExpire = 0;
1156 pCurrent->pHandler(pCurrent->opaque);
1157 }
1158 pCurrent = pNext;
1159 }
1160}
1161
1162/**
1163 * Converts slirp representation of poll events to host representation.
1164 *
1165 * @param iEvents Integer representing slirp type poll events.
1166 *
1167 * @returns Integer representing host type poll events.
1168 */
1169static short drvNAT_PollEventSlirpToHost(int iEvents)
1170{
1171 short iRet = 0;
1172#ifndef RT_OS_WINDOWS
1173 if (iEvents & SLIRP_POLL_IN) iRet |= POLLIN;
1174 if (iEvents & SLIRP_POLL_OUT) iRet |= POLLOUT;
1175 if (iEvents & SLIRP_POLL_PRI) iRet |= POLLPRI;
1176 if (iEvents & SLIRP_POLL_ERR) iRet |= POLLERR;
1177 if (iEvents & SLIRP_POLL_HUP) iRet |= POLLHUP;
1178#else
1179 if (iEvents & SLIRP_POLL_IN) iRet |= (POLLRDNORM | POLLRDBAND);
1180 if (iEvents & SLIRP_POLL_OUT) iRet |= POLLWRNORM;
1181 if (iEvents & SLIRP_POLL_PRI) iRet |= (POLLIN);
1182 if (iEvents & SLIRP_POLL_ERR) iRet |= 0;
1183 if (iEvents & SLIRP_POLL_HUP) iRet |= 0;
1184#endif
1185 return iRet;
1186}
1187
1188/**
1189 * Converts host representation of poll events to slirp representation.
1190 *
1191 * @param iEvents Integer representing host type poll events.
1192 *
1193 * @returns Integer representing slirp type poll events.
1194 *
1195 * @thread ?
1196 */
1197static int drvNAT_PollEventHostToSlirp(int iEvents) {
1198 int iRet = 0;
1199#ifndef RT_OS_WINDOWS
1200 if (iEvents & POLLIN) iRet |= SLIRP_POLL_IN;
1201 if (iEvents & POLLOUT) iRet |= SLIRP_POLL_OUT;
1202 if (iEvents & POLLPRI) iRet |= SLIRP_POLL_PRI;
1203 if (iEvents & POLLERR) iRet |= SLIRP_POLL_ERR;
1204 if (iEvents & POLLHUP) iRet |= SLIRP_POLL_HUP;
1205#else
1206 if (iEvents & (POLLRDNORM | POLLRDBAND)) iRet |= SLIRP_POLL_IN;
1207 if (iEvents & POLLWRNORM) iRet |= SLIRP_POLL_OUT;
1208 if (iEvents & (POLLPRI)) iRet |= SLIRP_POLL_PRI;
1209 if (iEvents & POLLERR) iRet |= SLIRP_POLL_ERR;
1210 if (iEvents & POLLHUP) iRet |= SLIRP_POLL_HUP;
1211#endif
1212 return iRet;
1213}
1214
1215
1216/*
1217 * Libslirp Callbacks
1218 */
1219/** @todo r=bird: None of these require DECLCALLBACK as such, since the libslirp
1220 * structure they're used with doesn't use DECLCALLBACKMEMBER or similar. */
1221/**
1222 * Callback called by libslirp to send packet into guest.
1223 *
1224 * @param pvBuf Pointer to packet buffer.
1225 * @param cb Size of packet.
1226 * @param pvUser Pointer to NAT State context.
1227 *
1228 * @returns Size of packet received or -1 on error.
1229 *
1230 * @thread ?
1231 */
1232static DECLCALLBACK(ssize_t) drvNAT_SendPacketCb(const void *pvBuf, ssize_t cb, void *pvUser /* PDRVNAT */)
1233{
1234 PDRVNAT const pThis = (PDRVNAT)pvUser;
1235 Assert(pThis);
1236
1237 void * const pvNewBuf = RTMemDup(pvBuf, cb);
1238 AssertReturn(pvNewBuf, -1);
1239
1240 LogFlow(("slirp_output BEGIN %p %d\n", pvNewBuf, cb));
1241 Log6(("slirp_output: pvNewBuf=%p cb=%#x (pThis=%p)\n"
1242 "%.*Rhxd\n", pvNewBuf, cb, pThis, cb, pvNewBuf));
1243
1244 /* don't queue new requests when the NAT thread is about to stop */
1245 if (pThis->pSlirpThread->enmState != PDMTHREADSTATE_RUNNING)
1246 return -1;
1247
1248 ASMAtomicIncU32(&pThis->cPkts);
1249 int rc = RTReqQueueCallEx(pThis->hRecvReqQueue, NULL /*ppReq*/, 0 /*cMillies*/, RTREQFLAGS_VOID | RTREQFLAGS_NO_WAIT,
1250 (PFNRT)drvNATRecvWorker, 3, pThis, pvNewBuf, cb);
1251 AssertRCStmt(rc, RTMemFree(pvNewBuf));
1252 drvNATRecvWakeup(pThis->pDrvIns, pThis->pRecvThread);
1253
1254 /** @todo r=bird: explain why we wake up the other thread here? */
1255 drvNATNotifyNATThread(pThis, "drvNAT_SendPacketCb");
1256
1257 STAM_COUNTER_INC(&pThis->StatQueuePktSent);
1258 LogFlowFuncLeave();
1259 return cb;
1260}
1261
1262/**
1263 * Callback called by libslirp when the guest does something wrong.
1264 *
1265 * @param pMsg Error message string.
1266 * @param pvUser Pointer to NAT State context.
1267 *
1268 * @thread ?
1269 */
1270static DECLCALLBACK(void) drvNAT_GuestErrorCb(const char *pszMsg, void *pvUser)
1271{
1272 /* Note! This is _just_ libslirp complaining about odd guest behaviour.
1273 It is nothing we need to create popup messages in the GUI about. */
1274 LogRelMax(250, ("NAT Guest Error: %s\n", pszMsg));
1275 RT_NOREF(pvUser);
1276}
1277
1278/**
1279 * Callback called by libslirp to get the current timestamp in nanoseconds.
1280 *
1281 * @param pvUser Pointer to NAT State context.
1282 *
1283 * @returns 64-bit signed integer representing time in nanoseconds.
1284 */
1285static DECLCALLBACK(int64_t) drvNAT_ClockGetNsCb(void *pvUser)
1286{
1287 RT_NOREF(pvUser);
1288 return (int64_t)RTTimeNanoTS();
1289}
1290
1291/**
1292 * Callback called by slirp to create a new timer and insert it into the given list.
1293 *
1294 * @param slirpTimeCb Callback function supplied to the new timer upon timer expiry.
1295 * Called later by the timeout handler.
1296 * @param cb_opaque Opaque object supplied to slirpTimeCb when called. Should be
1297 * Identical to the opaque parameter.
1298 * @param opaque Pointer to NAT State context.
1299 *
1300 * @returns Pointer to new timer.
1301 */
1302static DECLCALLBACK(void *) drvNAT_TimerNewCb(SlirpTimerCb slirpTimeCb, void *cb_opaque, void *opaque)
1303{
1304 PDRVNAT pThis = (PDRVNAT)opaque;
1305 Assert(pThis);
1306
1307 SlirpTimer * const pNewTimer = (SlirpTimer *)RTMemAlloc(sizeof(SlirpTimer));
1308 if (pNewTimer)
1309 {
1310 pNewTimer->msExpire = 0;
1311 pNewTimer->pHandler = slirpTimeCb;
1312 pNewTimer->opaque = cb_opaque;
1313 /** @todo r=bird: Not thread safe. Assumes pSlirpThread */
1314 pNewTimer->next = pThis->pNATState->pTimerHead;
1315 pThis->pNATState->pTimerHead = pNewTimer;
1316 }
1317 return pNewTimer;
1318}
1319
1320/**
1321 * Callback called by slirp to free a timer.
1322 *
1323 * @param pvTimer Pointer to slirpTimer object to be freed.
1324 * @param pvUser Pointer to NAT State context.
1325 */
1326static DECLCALLBACK(void) drvNAT_TimerFreeCb(void *pvTimer, void *pvUser)
1327{
1328 PDRVNAT const pThis = (PDRVNAT)pvUser;
1329 SlirpTimer * const pTimer = (SlirpTimer *)pvTimer;
1330 Assert(pThis);
1331 /** @todo r=bird: Not thread safe. Assumes pSlirpThread */
1332
1333 SlirpTimer *pPrev = NULL;
1334 SlirpTimer *pCurrent = pThis->pNATState->pTimerHead;
1335 while (pCurrent != NULL)
1336 {
1337 if (pCurrent == pTimer)
1338 {
1339 /* unlink it. */
1340 if (!pPrev)
1341 pThis->pNATState->pTimerHead = pCurrent->next;
1342 else
1343 pPrev->next = pCurrent->next;
1344 pCurrent->next = NULL;
1345 RTMemFree(pCurrent);
1346 return;
1347 }
1348
1349 /* advance */
1350 pPrev = pCurrent;
1351 pCurrent = pCurrent->next;
1352 }
1353 Assert(!pTimer);
1354}
1355
1356/**
1357 * Callback called by slirp to modify a timer.
1358 *
1359 * @param pvTimer Pointer to slirpTimer object to be modified.
1360 * @param msNewDeadlineTs The new absolute expiration time in milliseconds.
1361 * Zero stops it.
1362 * @param pvUser Pointer to NAT State context.
1363 */
1364static DECLCALLBACK(void) drvNAT_TimerModCb(void *pvTimer, int64_t msNewDeadlineTs, void *pvUser)
1365{
1366 SlirpTimer * const pTimer = (SlirpTimer *)pvTimer;
1367 /** @todo r=bird: ASSUMES pSlirpThread, otherwise it may need to be woken up! */
1368 pTimer->msExpire = msNewDeadlineTs;
1369 RT_NOREF(pvUser);
1370}
1371
1372/**
1373 * Callback called by slirp when there is I/O that needs to happen.
1374 *
1375 * @param opaque Pointer to NAT State context.
1376 */
1377static DECLCALLBACK(void) drvNAT_NotifyCb(void *opaque)
1378{
1379 PDRVNAT pThis = (PDRVNAT)opaque;
1380 drvNATNotifyNATThread(pThis, "drvNAT_NotifyCb");
1381}
1382
1383/**
1384 * Registers poll. Unused function (other than logging).
1385 */
1386static DECLCALLBACK(void) drvNAT_RegisterPoll(int fd, void *opaque)
1387{
1388 RT_NOREF(fd, opaque);
1389 Log4(("Poll registered: fd=%d\n", fd));
1390}
1391
1392/**
1393 * Unregisters poll. Unused function (other than logging).
1394 */
1395static DECLCALLBACK(void) drvNAT_UnregisterPoll(int fd, void *opaque)
1396{
1397 RT_NOREF(fd, opaque);
1398 Log4(("Poll unregistered: fd=%d\n", fd));
1399}
1400
1401/**
1402 * Callback function to add entry to pollfd array.
1403 *
1404 * @param iFd Integer of system file descriptor of socket.
1405 * (on windows, this is a VBox internal, not system, value).
1406 * @param iEvents Integer of slirp type poll events.
1407 * @param opaque Pointer to NAT State context.
1408 *
1409 * @returns Index of latest pollfd entry.
1410 *
1411 * @thread ?
1412 */
1413static DECLCALLBACK(int) drvNAT_AddPollCb(int iFd, int iEvents, void *opaque)
1414{
1415 PDRVNAT pThis = (PDRVNAT)opaque;
1416
1417 if (pThis->pNATState->nsock + 1 >= pThis->pNATState->uPollCap)
1418 {
1419 size_t cbNew = pThis->pNATState->uPollCap * 2 * sizeof(struct pollfd);
1420 struct pollfd *pvNew = (struct pollfd *)RTMemRealloc(pThis->pNATState->polls, cbNew);
1421 if (pvNew)
1422 {
1423 pThis->pNATState->polls = pvNew;
1424 pThis->pNATState->uPollCap *= 2;
1425 }
1426 else
1427 return -1;
1428 }
1429
1430 unsigned int uIdx = pThis->pNATState->nsock;
1431 Assert(uIdx < INT_MAX);
1432#ifdef RT_OS_WINDOWS
1433 pThis->pNATState->polls[uIdx].fd = libslirp_wrap_RTHandleTableLookup(iFd);
1434#else
1435 pThis->pNATState->polls[uIdx].fd = iFd;
1436#endif
1437 pThis->pNATState->polls[uIdx].events = drvNAT_PollEventSlirpToHost(iEvents);
1438 pThis->pNATState->polls[uIdx].revents = 0;
1439 pThis->pNATState->nsock += 1;
1440 return uIdx;
1441}
1442
1443/**
1444 * Get translated revents from a poll at a given index.
1445 *
1446 * @param idx Integer index of poll.
1447 * @param opaque Pointer to NAT State context.
1448 *
1449 * @returns Integer representing transalted revents.
1450 *
1451 * @thread ?
1452 */
1453static DECLCALLBACK(int) drvNAT_GetREventsCb(int idx, void *opaque)
1454{
1455 PDRVNAT pThis = (PDRVNAT)opaque;
1456 struct pollfd* polls = pThis->pNATState->polls;
1457 return drvNAT_PollEventHostToSlirp(polls[idx].revents);
1458}
1459
1460/**
1461 * Contructor/Destructor
1462 */
1463/**
1464 * Destruct a driver instance.
1465 *
1466 * Most VM resources are freed by the VM. This callback is provided so that any non-VM
1467 * resources can be freed correctly.
1468 *
1469 * @param pDrvIns The driver instance data.
1470 */
1471static DECLCALLBACK(void) drvNATDestruct(PPDMDRVINS pDrvIns)
1472{
1473 PDRVNAT pThis = PDMINS_2_DATA(pDrvIns, PDRVNAT);
1474 LogFlow(("drvNATDestruct:\n"));
1475 PDMDRV_CHECK_VERSIONS_RETURN_VOID(pDrvIns);
1476
1477 SlirpState * const pNATState = pThis->pNATState;
1478 if (pNATState)
1479 {
1480 if (pNATState->pSlirp)
1481 {
1482 slirp_cleanup(pNATState->pSlirp);
1483 pNATState->pSlirp = NULL;
1484 }
1485
1486#ifdef VBOX_WITH_STATISTICS
1487# define DRV_PROFILE_COUNTER(name, dsc) DEREGISTER_COUNTER(name, pThis)
1488# define DRV_COUNTING_COUNTER(name, dsc) DEREGISTER_COUNTER(name, pThis)
1489# include "slirp/counters.h"
1490#endif
1491 RTMemFree(pNATState->polls);
1492 pNATState->polls = NULL;
1493
1494 RTMemFree(pNATState);
1495 pThis->pNATState = NULL;
1496 }
1497
1498 RTReqQueueDestroy(pThis->hSlirpReqQueue);
1499 pThis->hSlirpReqQueue = NIL_RTREQQUEUE;
1500
1501 RTReqQueueDestroy(pThis->hRecvReqQueue);
1502 pThis->hRecvReqQueue = NIL_RTREQQUEUE;
1503
1504 RTSemEventDestroy(pThis->hEventRecv);
1505 pThis->hEventRecv = NIL_RTSEMEVENT;
1506
1507 if (RTCritSectIsInitialized(&pThis->DevAccessLock))
1508 RTCritSectDelete(&pThis->DevAccessLock);
1509
1510 if (RTCritSectIsInitialized(&pThis->XmitLock))
1511 RTCritSectDelete(&pThis->XmitLock);
1512
1513#ifndef RT_OS_WINDOWS
1514 RTPipeClose(pThis->hPipeRead);
1515 RTPipeClose(pThis->hPipeWrite);
1516 pThis->hPipeRead = NIL_RTPIPE;
1517 pThis->hPipeWrite = NIL_RTPIPE;
1518#endif
1519}
1520
1521/**
1522 * Construct a NAT network transport driver instance.
1523 *
1524 * @copydoc FNPDMDRVCONSTRUCT
1525 */
1526static DECLCALLBACK(int) drvNATConstruct(PPDMDRVINS pDrvIns, PCFGMNODE pCfg, uint32_t fFlags)
1527{
1528 RT_NOREF(fFlags);
1529 PDMDRV_CHECK_VERSIONS_RETURN(pDrvIns);
1530 PDRVNAT pThis = PDMINS_2_DATA(pDrvIns, PDRVNAT);
1531
1532 /*
1533 * Init the static parts.
1534 */
1535 pThis->pDrvIns = pDrvIns;
1536 pThis->hSlirpReqQueue = NIL_RTREQQUEUE;
1537 pThis->hEventRecv = NIL_RTSEMEVENT;
1538 pThis->hRecvReqQueue = NIL_RTREQQUEUE;
1539#ifndef RT_OS_WINDOWS
1540 pThis->hPipeRead = NIL_RTPIPE;
1541 pThis->hPipeWrite = NIL_RTPIPE;
1542#endif
1543
1544 SlirpState * const pNATState = (SlirpState *)RTMemAllocZ(sizeof(*pNATState));
1545 if (pNATState == NULL)
1546 return VERR_NO_MEMORY;
1547 pThis->pNATState = pNATState;
1548 pNATState->nsock = 0;
1549 pNATState->pTimerHead = NULL;
1550 pNATState->polls = (struct pollfd *)RTMemAllocZ(64 * sizeof(struct pollfd));
1551 AssertReturn(pNATState->polls, VERR_NO_MEMORY);
1552 pNATState->uPollCap = 64;
1553
1554 /* IBase */
1555 pDrvIns->IBase.pfnQueryInterface = drvNATQueryInterface;
1556
1557 /* INetwork */
1558 pThis->INetworkUp.pfnBeginXmit = drvNATNetworkUp_BeginXmit;
1559 pThis->INetworkUp.pfnAllocBuf = drvNATNetworkUp_AllocBuf;
1560 pThis->INetworkUp.pfnFreeBuf = drvNATNetworkUp_FreeBuf;
1561 pThis->INetworkUp.pfnSendBuf = drvNATNetworkUp_SendBuf;
1562 pThis->INetworkUp.pfnEndXmit = drvNATNetworkUp_EndXmit;
1563 pThis->INetworkUp.pfnSetPromiscuousMode = drvNATNetworkUp_SetPromiscuousMode;
1564 pThis->INetworkUp.pfnNotifyLinkChanged = drvNATNetworkUp_NotifyLinkChanged;
1565
1566 /* NAT engine configuration */
1567 pThis->INetworkNATCfg.pfnRedirectRuleCommand = drvNATNetworkNatConfigRedirect;
1568 pThis->INetworkNATCfg.pfnNotifyDnsChanged = drvNATNotifyDnsChanged;
1569
1570 /*
1571 * Validate the config.
1572 */
1573 PDMDRV_VALIDATE_CONFIG_RETURN(pDrvIns,
1574 "PassDomain"
1575 "|TFTPPrefix"
1576 "|BootFile"
1577 "|Network"
1578 "|NextServer"
1579 "|DNSProxy"
1580 "|BindIP"
1581 "|UseHostResolver"
1582 "|SlirpMTU"
1583 "|AliasMode"
1584 "|SockRcv"
1585 "|SockSnd"
1586 "|TcpRcv"
1587 "|TcpSnd"
1588 "|ICMPCacheLimit"
1589 "|SoMaxConnection"
1590 "|LocalhostReachable"
1591 "|HostResolverMappings"
1592 "|ForwardBroadcast"
1593 , "PortForwarding");
1594
1595 LogRel(("NAT: These CFGM parameters are currently not supported when using NAT:\n"
1596 " DNSProxy\n"
1597 " UseHostResolver\n"
1598 " AliasMode\n"
1599 " SockRcv\n"
1600 " SockSnd\n"
1601 " TcpRcv\n"
1602 " TcpSnd\n"
1603 " ICMPCacheLimit\n"
1604 " HostResolverMappings\n"
1605 ));
1606
1607 /*
1608 * Get the configuration settings.
1609 */
1610 int rc;
1611 /** @todo clean up the macros used here. S32 != int. Use defaults. ++ */
1612
1613 bool fPassDomain = true;
1614 GET_BOOL(rc, pDrvIns, pCfg, "PassDomain", fPassDomain);
1615 pNATState->fPassDomain = fPassDomain;
1616
1617 bool fForwardBroadcast = false;
1618 GET_BOOL(rc, pDrvIns, pCfg, "ForwardBroadcast", fForwardBroadcast);
1619
1620 GET_STRING_ALLOC(rc, pDrvIns, pCfg, "TFTPPrefix", pThis->pszTFTPPrefix);
1621 GET_STRING_ALLOC(rc, pDrvIns, pCfg, "BootFile", pThis->pszBootFile);
1622 GET_STRING_ALLOC(rc, pDrvIns, pCfg, "NextServer", pThis->pszNextServer);
1623
1624 int fDNSProxy = 0;
1625 GET_S32(rc, pDrvIns, pCfg, "DNSProxy", fDNSProxy);
1626 unsigned int MTU = 1500;
1627 GET_U32(rc, pDrvIns, pCfg, "SlirpMTU", MTU);
1628 int iIcmpCacheLimit = 100;
1629 GET_S32(rc, pDrvIns, pCfg, "ICMPCacheLimit", iIcmpCacheLimit);
1630 bool fLocalhostReachable = false;
1631 GET_BOOL(rc, pDrvIns, pCfg, "LocalhostReachable", fLocalhostReachable);
1632 int i32SoMaxConn = 10;
1633 GET_S32(rc, pDrvIns, pCfg, "SoMaxConnection", i32SoMaxConn);
1634
1635 /*
1636 * Query the network port interface.
1637 */
1638 pThis->pIAboveNet = PDMIBASE_QUERY_INTERFACE(pDrvIns->pUpBase, PDMINETWORKDOWN);
1639 if (!pThis->pIAboveNet)
1640 return PDMDRV_SET_ERROR(pDrvIns, VERR_PDM_MISSING_INTERFACE_ABOVE,
1641 N_("Configuration error: the above device/driver didn't export the network port interface"));
1642 pThis->pIAboveConfig = PDMIBASE_QUERY_INTERFACE(pDrvIns->pUpBase, PDMINETWORKCONFIG);
1643 if (!pThis->pIAboveConfig)
1644 return PDMDRV_SET_ERROR(pDrvIns, VERR_PDM_MISSING_INTERFACE_ABOVE,
1645 N_("Configuration error: the above device/driver didn't export the network config interface"));
1646
1647 /* Generate a network address for this network card. */
1648 char szNetwork[32]; /* xxx.xxx.xxx.xxx/yy */
1649 GET_STRING(rc, pDrvIns, pCfg, "Network", szNetwork[0], sizeof(szNetwork));
1650 if (rc == VERR_CFGM_VALUE_NOT_FOUND)
1651 return PDMDrvHlpVMSetError(pDrvIns, rc, RT_SRC_POS, N_("NAT%d: Configuration error: missing network"),
1652 pDrvIns->iInstance);
1653
1654 RTNETADDRIPV4 Network, Netmask;
1655 rc = RTCidrStrToIPv4(szNetwork, &Network, &Netmask);
1656 if (RT_FAILURE(rc))
1657 return PDMDrvHlpVMSetError(pDrvIns, rc, RT_SRC_POS,
1658 N_("NAT#%d: Configuration error: network '%s' describes not a valid IPv4 network"),
1659 pDrvIns->iInstance, szNetwork);
1660
1661 /*
1662 * Construct Libslirp Config.
1663 */
1664 LogFlow(("Here is what is coming out of the vbox config (NAT#%d):\n"
1665 " Network: %RTnaipv4\n"
1666 " Netmask: %RTnaipv4\n",
1667 pDrvIns->iInstance, RT_H2BE_U32(Network.u), RT_H2BE_U32(Netmask.u)));
1668
1669 /* IPv4: */
1670 struct in_addr vnetwork = RTNetIPv4AddrHEToInAddr(&Network);
1671 struct in_addr vnetmask = RTNetIPv4AddrHEToInAddr(&Netmask);
1672
1673 RTNETADDRIPV4 NetTemp = Network;
1674 NetTemp.u |= 2; /* Usually 10.0.2.2 */
1675 struct in_addr vhost = RTNetIPv4AddrHEToInAddr(&NetTemp);
1676
1677 NetTemp = Network;
1678 NetTemp.u |= 15; /* Usually 10.0.2.15 */
1679 struct in_addr vdhcp_start = RTNetIPv4AddrHEToInAddr(&NetTemp);
1680
1681 NetTemp = Network;
1682 NetTemp.u |= 3; /* Usually 10.0.2.3 */
1683 struct in_addr vnameserver = RTNetIPv4AddrHEToInAddr(&NetTemp);
1684
1685 SlirpConfig slirpCfg = { 0 };
1686 static SlirpCb slirpCallbacks = { 0 };
1687
1688 slirpCfg.version = 4;
1689 slirpCfg.restricted = false;
1690 slirpCfg.in_enabled = true;
1691 slirpCfg.vnetwork = vnetwork;
1692 slirpCfg.vnetmask = vnetmask;
1693 slirpCfg.vhost = vhost;
1694 slirpCfg.in6_enabled = true;
1695
1696 /* IPv6: Use the same prefix as the NAT Network default:
1697 [fd17:625c:f037:XXXX::/64] - RFC 4193 (ULA) Locally Assigned
1698 Global ID where XXXX, 16 bit Subnet ID, are two bytes from the
1699 middle of the IPv4 address, e.g. :0002: for 10.0.2.1. */
1700 inet_pton(AF_INET6, "fd17:625c:f037:0::", &slirpCfg.vprefix_addr6);
1701 inet_pton(AF_INET6, "fd17:625c:f037:0::2", &slirpCfg.vhost6);
1702 inet_pton(AF_INET6, "fd17:625c:f037:0::3", &slirpCfg.vnameserver6);
1703 slirpCfg.vprefix_len = 64;
1704
1705 /* Copy the middle of the IPv4 addresses to the IPv6 addresses. */
1706 slirpCfg.vprefix_addr6.s6_addr[6] = RT_BYTE2(vhost.s_addr);
1707 slirpCfg.vprefix_addr6.s6_addr[7] = RT_BYTE3(vhost.s_addr);
1708 slirpCfg.vhost6.s6_addr[6] = RT_BYTE2(vhost.s_addr);
1709 slirpCfg.vhost6.s6_addr[7] = RT_BYTE3(vhost.s_addr);
1710 slirpCfg.vnameserver6.s6_addr[6] = RT_BYTE2(vnameserver.s_addr);
1711 slirpCfg.vnameserver6.s6_addr[7] = RT_BYTE3(vnameserver.s_addr);
1712
1713 slirpCfg.vhostname = "vbox";
1714 slirpCfg.tftp_server_name = pThis->pszNextServer;
1715 slirpCfg.tftp_path = pThis->pszTFTPPrefix;
1716 slirpCfg.bootfile = pThis->pszBootFile;
1717 slirpCfg.vdhcp_start = vdhcp_start;
1718 slirpCfg.vnameserver = vnameserver;
1719 slirpCfg.if_mtu = MTU;
1720
1721 slirpCfg.vdnssearch = NULL;
1722 slirpCfg.vdomainname = NULL;
1723 slirpCfg.disable_host_loopback = !fLocalhostReachable;
1724 slirpCfg.fForwardBroadcast = fForwardBroadcast;
1725 slirpCfg.iSoMaxConn = i32SoMaxConn;
1726
1727 slirpCallbacks.send_packet = drvNAT_SendPacketCb;
1728 slirpCallbacks.guest_error = drvNAT_GuestErrorCb;
1729 slirpCallbacks.clock_get_ns = drvNAT_ClockGetNsCb;
1730 slirpCallbacks.timer_new = drvNAT_TimerNewCb;
1731 slirpCallbacks.timer_free = drvNAT_TimerFreeCb;
1732 slirpCallbacks.timer_mod = drvNAT_TimerModCb;
1733 slirpCallbacks.register_poll_fd = drvNAT_RegisterPoll;
1734 slirpCallbacks.unregister_poll_fd = drvNAT_UnregisterPoll;
1735 slirpCallbacks.notify = drvNAT_NotifyCb;
1736 slirpCallbacks.init_completed = NULL;
1737 slirpCallbacks.timer_new_opaque = NULL;
1738
1739 /*
1740 * Initialize Slirp
1741 */
1742 Slirp * const pSlirp = slirp_new(/* cfg */ &slirpCfg, /* callbacks */ &slirpCallbacks, /* opaque */ pThis);
1743 if (!pSlirp)
1744 return PDMDRV_SET_ERROR(pDrvIns, VERR_INTERNAL_ERROR_4,
1745 N_("Configuration error: libslirp failed to create new instance - probably misconfiguration"));
1746
1747 pNATState->pSlirp = pSlirp;
1748
1749 rc = drvNATConstructRedir(pDrvIns->iInstance, pThis, pCfg, &Network);
1750 AssertLogRelRCReturn(rc, rc);
1751
1752 rc = PDMDrvHlpSSMRegisterLoadDone(pDrvIns, NULL);
1753 AssertLogRelRCReturn(rc, rc);
1754
1755 rc = RTReqQueueCreate(&pThis->hSlirpReqQueue);
1756 AssertLogRelRCReturn(rc, rc);
1757
1758 rc = RTReqQueueCreate(&pThis->hRecvReqQueue);
1759 AssertLogRelRCReturn(rc, rc);
1760
1761 rc = PDMDrvHlpThreadCreate(pDrvIns, &pThis->pRecvThread, pThis, drvNATRecv,
1762 drvNATRecvWakeup, 256 * _1K, RTTHREADTYPE_IO, "NATRX");
1763 AssertRCReturn(rc, rc);
1764
1765 rc = RTSemEventCreate(&pThis->hEventRecv);
1766 AssertRCReturn(rc, rc);
1767
1768 rc = RTCritSectInit(&pThis->DevAccessLock);
1769 AssertRCReturn(rc, rc);
1770
1771 rc = RTCritSectInit(&pThis->XmitLock);
1772 AssertRCReturn(rc, rc);
1773
1774 char szTmp[128];
1775 RTStrPrintf(szTmp, sizeof(szTmp), "nat%d", pDrvIns->iInstance);
1776 PDMDrvHlpDBGFInfoRegister(pDrvIns, szTmp, "NAT info.", drvNATInfo);
1777
1778#ifdef VBOX_WITH_STATISTICS
1779# define DRV_PROFILE_COUNTER(name, dsc) REGISTER_COUNTER(name, pThis, STAMTYPE_PROFILE, STAMUNIT_TICKS_PER_CALL, dsc)
1780# define DRV_COUNTING_COUNTER(name, dsc) REGISTER_COUNTER(name, pThis, STAMTYPE_COUNTER, STAMUNIT_COUNT, dsc)
1781# include "slirp/counters.h"
1782#endif
1783
1784#ifdef RT_OS_WINDOWS
1785 /* Create the wakeup socket pair (idx=0 is write, idx=1 is read). */
1786 pThis->ahWakeupSockPair[0] = INVALID_SOCKET;
1787 pThis->ahWakeupSockPair[1] = INVALID_SOCKET;
1788 rc = RTWinSocketPair(AF_INET, SOCK_DGRAM, 0, pThis->ahWakeupSockPair);
1789 AssertRCReturn(rc, rc);
1790
1791 uint32_t hReadFd = 0;
1792 uint32_t hWriteFd = 0;
1793
1794 rc = libslirp_wrap_RTHandleTableAlloc(pThis->ahWakeupSockPair[0], &hReadFd);
1795 AssertRCReturn(rc, rc);
1796
1797 rc = libslirp_wrap_RTHandleTableAlloc(pThis->ahWakeupSockPair[1], &hWriteFd);
1798 AssertRCReturn(rc, rc);
1799
1800 Log4Func(("Created wakeup socket pair.\nSocket details - read:%d, write%d\n \
1801 Handle details - read:%d, write%d\n", pThis->ahWakeupSockPair[0],
1802 pThis->ahWakeupSockPair[1], hReadFd, hWriteFd));
1803
1804 /**
1805 * @todo r=jack: should probably use the internal handles up in the io
1806 * thread. Will fix (or just update libslirp and this translation stuff
1807 * might go away).
1808 */
1809#else
1810 /* Create the control pipe. */
1811 rc = RTPipeCreate(&pThis->hPipeRead, &pThis->hPipeWrite, 0 /*fFlags*/);
1812 AssertRCReturn(rc, rc);
1813#endif
1814 /* initalize the notifier counter */
1815 pThis->cbWakeupNotifs = 0;
1816
1817 rc = PDMDrvHlpThreadCreate(pDrvIns, &pThis->pSlirpThread, pThis, drvNATAsyncIoThread,
1818 drvNATAsyncIoWakeup, 256 * _1K, RTTHREADTYPE_IO, "NAT");
1819 AssertRCReturn(rc, rc);
1820
1821 pThis->enmLinkState = pThis->enmLinkStateWant = PDMNETWORKLINKSTATE_UP;
1822
1823 return rc;
1824}
1825
1826/**
1827 * NAT network transport driver registration record.
1828 */
1829const PDMDRVREG g_DrvNATlibslirp =
1830{
1831 /* u32Version */
1832 PDM_DRVREG_VERSION,
1833 /* szName */
1834 "NAT",
1835 /* szRCMod */
1836 "",
1837 /* szR0Mod */
1838 "",
1839 /* pszDescription */
1840 "NATlibslrip Network Transport Driver",
1841 /* fFlags */
1842 PDM_DRVREG_FLAGS_HOST_BITS_DEFAULT,
1843 /* fClass. */
1844 PDM_DRVREG_CLASS_NETWORK,
1845 /* cMaxInstances */
1846 ~0U,
1847 /* cbInstance */
1848 sizeof(DRVNAT),
1849 /* pfnConstruct */
1850 drvNATConstruct,
1851 /* pfnDestruct */
1852 drvNATDestruct,
1853 /* pfnRelocate */
1854 NULL,
1855 /* pfnIOCtl */
1856 NULL,
1857 /* pfnPowerOn */
1858 NULL,
1859 /* pfnReset */
1860 NULL,
1861 /* pfnSuspend */
1862 NULL,
1863 /* pfnResume */
1864 NULL,
1865 /* pfnAttach */
1866 NULL,
1867 /* pfnDetach */
1868 NULL,
1869 /* pfnPowerOff */
1870 NULL,
1871 /* pfnSoftReset */
1872 NULL,
1873 /* u32EndVersion */
1874 PDM_DRVREG_VERSION
1875};
Note: See TracBrowser for help on using the repository browser.

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