VirtualBox

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

Last change on this file since 109091 was 109079, checked in by vboxsync, 8 days ago

lib/libslirp-4.9.0,Devices/Network: Switch to libslirp-4.9.0, bugref:10268

  • Property svn:eol-style set to native
  • Property svn:keywords set to Author Date Id Revision
File size: 65.4 KB
Line 
1/* $Id: DrvNATlibslirp.cpp 109079 2025-04-25 09:52:51Z 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(slirp_os_socket hFd, 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 uint32_t cMsTimeout = DRVNAT_DEFAULT_TIMEOUT;
774 slirp_pollfds_fill_socket(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(slirp_os_socket socket, void *opaque)
1387{
1388 RT_NOREF(socket, opaque);
1389#ifdef RT_OS_WINDOWS
1390 Log4(("Poll registered: fd=%p\n", socket));
1391#else
1392 Log4(("Poll registered: fd=%d\n", socket));
1393#endif
1394}
1395
1396/**
1397 * Unregisters poll. Unused function (other than logging).
1398 */
1399static DECLCALLBACK(void) drvNAT_UnregisterPoll(slirp_os_socket socket, void *opaque)
1400{
1401 RT_NOREF(socket, opaque);
1402#ifdef RT_OS_WINDOWS
1403 Log4(("Poll unregistered: fd=%p\n", socket));
1404#else
1405 Log4(("Poll unregistered: fd=%d\n", socket));
1406#endif
1407}
1408
1409/**
1410 * Callback function to add entry to pollfd array.
1411 *
1412 * @param iFd Integer of system file descriptor of socket.
1413 * (on windows, this is a VBox internal, not system, value).
1414 * @param iEvents Integer of slirp type poll events.
1415 * @param opaque Pointer to NAT State context.
1416 *
1417 * @returns Index of latest pollfd entry.
1418 *
1419 * @thread ?
1420 */
1421static DECLCALLBACK(int) drvNAT_AddPollCb(slirp_os_socket hFd, int iEvents, void *opaque)
1422{
1423 PDRVNAT pThis = (PDRVNAT)opaque;
1424
1425 if (pThis->pNATState->nsock + 1 >= pThis->pNATState->uPollCap)
1426 {
1427 size_t cbNew = pThis->pNATState->uPollCap * 2 * sizeof(struct pollfd);
1428 struct pollfd *pvNew = (struct pollfd *)RTMemRealloc(pThis->pNATState->polls, cbNew);
1429 if (pvNew)
1430 {
1431 pThis->pNATState->polls = pvNew;
1432 pThis->pNATState->uPollCap *= 2;
1433 }
1434 else
1435 return -1;
1436 }
1437
1438 unsigned int uIdx = pThis->pNATState->nsock;
1439 Assert(uIdx < INT_MAX);
1440 pThis->pNATState->polls[uIdx].fd = hFd;
1441 pThis->pNATState->polls[uIdx].events = drvNAT_PollEventSlirpToHost(iEvents);
1442 pThis->pNATState->polls[uIdx].revents = 0;
1443 pThis->pNATState->nsock += 1;
1444 return uIdx;
1445}
1446
1447/**
1448 * Get translated revents from a poll at a given index.
1449 *
1450 * @param idx Integer index of poll.
1451 * @param opaque Pointer to NAT State context.
1452 *
1453 * @returns Integer representing transalted revents.
1454 *
1455 * @thread ?
1456 */
1457static DECLCALLBACK(int) drvNAT_GetREventsCb(int idx, void *opaque)
1458{
1459 PDRVNAT pThis = (PDRVNAT)opaque;
1460 struct pollfd* polls = pThis->pNATState->polls;
1461 return drvNAT_PollEventHostToSlirp(polls[idx].revents);
1462}
1463
1464/**
1465 * Contructor/Destructor
1466 */
1467/**
1468 * Destruct a driver instance.
1469 *
1470 * Most VM resources are freed by the VM. This callback is provided so that any non-VM
1471 * resources can be freed correctly.
1472 *
1473 * @param pDrvIns The driver instance data.
1474 */
1475static DECLCALLBACK(void) drvNATDestruct(PPDMDRVINS pDrvIns)
1476{
1477 PDRVNAT pThis = PDMINS_2_DATA(pDrvIns, PDRVNAT);
1478 LogFlow(("drvNATDestruct:\n"));
1479 PDMDRV_CHECK_VERSIONS_RETURN_VOID(pDrvIns);
1480
1481 SlirpState * const pNATState = pThis->pNATState;
1482 if (pNATState)
1483 {
1484 if (pNATState->pSlirp)
1485 {
1486 slirp_cleanup(pNATState->pSlirp);
1487 pNATState->pSlirp = NULL;
1488 }
1489
1490#ifdef VBOX_WITH_STATISTICS
1491# define DRV_PROFILE_COUNTER(name, dsc) DEREGISTER_COUNTER(name, pThis)
1492# define DRV_COUNTING_COUNTER(name, dsc) DEREGISTER_COUNTER(name, pThis)
1493# include "slirp/counters.h"
1494#endif
1495 RTMemFree(pNATState->polls);
1496 pNATState->polls = NULL;
1497
1498 RTMemFree(pNATState);
1499 pThis->pNATState = NULL;
1500 }
1501
1502 RTReqQueueDestroy(pThis->hSlirpReqQueue);
1503 pThis->hSlirpReqQueue = NIL_RTREQQUEUE;
1504
1505 RTReqQueueDestroy(pThis->hRecvReqQueue);
1506 pThis->hRecvReqQueue = NIL_RTREQQUEUE;
1507
1508 RTSemEventDestroy(pThis->hEventRecv);
1509 pThis->hEventRecv = NIL_RTSEMEVENT;
1510
1511 if (RTCritSectIsInitialized(&pThis->DevAccessLock))
1512 RTCritSectDelete(&pThis->DevAccessLock);
1513
1514 if (RTCritSectIsInitialized(&pThis->XmitLock))
1515 RTCritSectDelete(&pThis->XmitLock);
1516
1517#ifndef RT_OS_WINDOWS
1518 RTPipeClose(pThis->hPipeRead);
1519 RTPipeClose(pThis->hPipeWrite);
1520 pThis->hPipeRead = NIL_RTPIPE;
1521 pThis->hPipeWrite = NIL_RTPIPE;
1522#endif
1523}
1524
1525/**
1526 * Construct a NAT network transport driver instance.
1527 *
1528 * @copydoc FNPDMDRVCONSTRUCT
1529 */
1530static DECLCALLBACK(int) drvNATConstruct(PPDMDRVINS pDrvIns, PCFGMNODE pCfg, uint32_t fFlags)
1531{
1532 RT_NOREF(fFlags);
1533 PDMDRV_CHECK_VERSIONS_RETURN(pDrvIns);
1534 PDRVNAT pThis = PDMINS_2_DATA(pDrvIns, PDRVNAT);
1535
1536 /*
1537 * Init the static parts.
1538 */
1539 pThis->pDrvIns = pDrvIns;
1540 pThis->hSlirpReqQueue = NIL_RTREQQUEUE;
1541 pThis->hEventRecv = NIL_RTSEMEVENT;
1542 pThis->hRecvReqQueue = NIL_RTREQQUEUE;
1543#ifndef RT_OS_WINDOWS
1544 pThis->hPipeRead = NIL_RTPIPE;
1545 pThis->hPipeWrite = NIL_RTPIPE;
1546#endif
1547
1548 SlirpState * const pNATState = (SlirpState *)RTMemAllocZ(sizeof(*pNATState));
1549 if (pNATState == NULL)
1550 return VERR_NO_MEMORY;
1551 pThis->pNATState = pNATState;
1552 pNATState->nsock = 0;
1553 pNATState->pTimerHead = NULL;
1554 pNATState->polls = (struct pollfd *)RTMemAllocZ(64 * sizeof(struct pollfd));
1555 AssertReturn(pNATState->polls, VERR_NO_MEMORY);
1556 pNATState->uPollCap = 64;
1557
1558 /* IBase */
1559 pDrvIns->IBase.pfnQueryInterface = drvNATQueryInterface;
1560
1561 /* INetwork */
1562 pThis->INetworkUp.pfnBeginXmit = drvNATNetworkUp_BeginXmit;
1563 pThis->INetworkUp.pfnAllocBuf = drvNATNetworkUp_AllocBuf;
1564 pThis->INetworkUp.pfnFreeBuf = drvNATNetworkUp_FreeBuf;
1565 pThis->INetworkUp.pfnSendBuf = drvNATNetworkUp_SendBuf;
1566 pThis->INetworkUp.pfnEndXmit = drvNATNetworkUp_EndXmit;
1567 pThis->INetworkUp.pfnSetPromiscuousMode = drvNATNetworkUp_SetPromiscuousMode;
1568 pThis->INetworkUp.pfnNotifyLinkChanged = drvNATNetworkUp_NotifyLinkChanged;
1569
1570 /* NAT engine configuration */
1571 pThis->INetworkNATCfg.pfnRedirectRuleCommand = drvNATNetworkNatConfigRedirect;
1572 pThis->INetworkNATCfg.pfnNotifyDnsChanged = drvNATNotifyDnsChanged;
1573
1574 /*
1575 * Validate the config.
1576 */
1577 PDMDRV_VALIDATE_CONFIG_RETURN(pDrvIns,
1578 "PassDomain"
1579 "|TFTPPrefix"
1580 "|BootFile"
1581 "|Network"
1582 "|NextServer"
1583 "|DNSProxy"
1584 "|BindIP"
1585 "|UseHostResolver"
1586 "|SlirpMTU"
1587 "|AliasMode"
1588 "|SockRcv"
1589 "|SockSnd"
1590 "|TcpRcv"
1591 "|TcpSnd"
1592 "|ICMPCacheLimit"
1593 "|SoMaxConnection"
1594 "|LocalhostReachable"
1595 "|HostResolverMappings"
1596 "|ForwardBroadcast"
1597 , "PortForwarding");
1598
1599 LogRel(("NAT: These CFGM parameters are currently not supported when using NAT:\n"
1600 " DNSProxy\n"
1601 " UseHostResolver\n"
1602 " AliasMode\n"
1603 " SockRcv\n"
1604 " SockSnd\n"
1605 " TcpRcv\n"
1606 " TcpSnd\n"
1607 " ICMPCacheLimit\n"
1608 " HostResolverMappings\n"
1609 ));
1610
1611 /*
1612 * Get the configuration settings.
1613 */
1614 int rc;
1615 /** @todo clean up the macros used here. S32 != int. Use defaults. ++ */
1616
1617 bool fPassDomain = true;
1618 GET_BOOL(rc, pDrvIns, pCfg, "PassDomain", fPassDomain);
1619 pNATState->fPassDomain = fPassDomain;
1620
1621 bool fForwardBroadcast = false;
1622 GET_BOOL(rc, pDrvIns, pCfg, "ForwardBroadcast", fForwardBroadcast);
1623
1624 GET_STRING_ALLOC(rc, pDrvIns, pCfg, "TFTPPrefix", pThis->pszTFTPPrefix);
1625 GET_STRING_ALLOC(rc, pDrvIns, pCfg, "BootFile", pThis->pszBootFile);
1626 GET_STRING_ALLOC(rc, pDrvIns, pCfg, "NextServer", pThis->pszNextServer);
1627
1628 int fDNSProxy = 0;
1629 GET_S32(rc, pDrvIns, pCfg, "DNSProxy", fDNSProxy);
1630 unsigned int MTU = 1500;
1631 GET_U32(rc, pDrvIns, pCfg, "SlirpMTU", MTU);
1632 int iIcmpCacheLimit = 100;
1633 GET_S32(rc, pDrvIns, pCfg, "ICMPCacheLimit", iIcmpCacheLimit);
1634 bool fLocalhostReachable = false;
1635 GET_BOOL(rc, pDrvIns, pCfg, "LocalhostReachable", fLocalhostReachable);
1636 int i32SoMaxConn = 10;
1637 GET_S32(rc, pDrvIns, pCfg, "SoMaxConnection", i32SoMaxConn);
1638
1639 /*
1640 * Query the network port interface.
1641 */
1642 pThis->pIAboveNet = PDMIBASE_QUERY_INTERFACE(pDrvIns->pUpBase, PDMINETWORKDOWN);
1643 if (!pThis->pIAboveNet)
1644 return PDMDRV_SET_ERROR(pDrvIns, VERR_PDM_MISSING_INTERFACE_ABOVE,
1645 N_("Configuration error: the above device/driver didn't export the network port interface"));
1646 pThis->pIAboveConfig = PDMIBASE_QUERY_INTERFACE(pDrvIns->pUpBase, PDMINETWORKCONFIG);
1647 if (!pThis->pIAboveConfig)
1648 return PDMDRV_SET_ERROR(pDrvIns, VERR_PDM_MISSING_INTERFACE_ABOVE,
1649 N_("Configuration error: the above device/driver didn't export the network config interface"));
1650
1651 /* Generate a network address for this network card. */
1652 char szNetwork[32]; /* xxx.xxx.xxx.xxx/yy */
1653 GET_STRING(rc, pDrvIns, pCfg, "Network", szNetwork[0], sizeof(szNetwork));
1654 if (rc == VERR_CFGM_VALUE_NOT_FOUND)
1655 return PDMDrvHlpVMSetError(pDrvIns, rc, RT_SRC_POS, N_("NAT%d: Configuration error: missing network"),
1656 pDrvIns->iInstance);
1657
1658 RTNETADDRIPV4 Network, Netmask;
1659 rc = RTCidrStrToIPv4(szNetwork, &Network, &Netmask);
1660 if (RT_FAILURE(rc))
1661 return PDMDrvHlpVMSetError(pDrvIns, rc, RT_SRC_POS,
1662 N_("NAT#%d: Configuration error: network '%s' describes not a valid IPv4 network"),
1663 pDrvIns->iInstance, szNetwork);
1664
1665 /*
1666 * Construct Libslirp Config.
1667 */
1668 LogFlow(("Here is what is coming out of the vbox config (NAT#%d):\n"
1669 " Network: %RTnaipv4\n"
1670 " Netmask: %RTnaipv4\n",
1671 pDrvIns->iInstance, RT_H2BE_U32(Network.u), RT_H2BE_U32(Netmask.u)));
1672
1673 /* IPv4: */
1674 struct in_addr vnetwork = RTNetIPv4AddrHEToInAddr(&Network);
1675 struct in_addr vnetmask = RTNetIPv4AddrHEToInAddr(&Netmask);
1676
1677 RTNETADDRIPV4 NetTemp = Network;
1678 NetTemp.u |= 2; /* Usually 10.0.2.2 */
1679 struct in_addr vhost = RTNetIPv4AddrHEToInAddr(&NetTemp);
1680
1681 NetTemp = Network;
1682 NetTemp.u |= 15; /* Usually 10.0.2.15 */
1683 struct in_addr vdhcp_start = RTNetIPv4AddrHEToInAddr(&NetTemp);
1684
1685 NetTemp = Network;
1686 NetTemp.u |= 3; /* Usually 10.0.2.3 */
1687 struct in_addr vnameserver = RTNetIPv4AddrHEToInAddr(&NetTemp);
1688
1689 SlirpConfig slirpCfg = { 0 };
1690 static SlirpCb slirpCallbacks = { 0 };
1691
1692 slirpCfg.version = 6;
1693 slirpCfg.restricted = false;
1694 slirpCfg.in_enabled = true;
1695 slirpCfg.vnetwork = vnetwork;
1696 slirpCfg.vnetmask = vnetmask;
1697 slirpCfg.vhost = vhost;
1698 slirpCfg.in6_enabled = true;
1699
1700 /* IPv6: Use the same prefix as the NAT Network default:
1701 [fd17:625c:f037:XXXX::/64] - RFC 4193 (ULA) Locally Assigned
1702 Global ID where XXXX, 16 bit Subnet ID, are two bytes from the
1703 middle of the IPv4 address, e.g. :0002: for 10.0.2.1. */
1704 inet_pton(AF_INET6, "fd17:625c:f037:0::", &slirpCfg.vprefix_addr6);
1705 inet_pton(AF_INET6, "fd17:625c:f037:0::2", &slirpCfg.vhost6);
1706 inet_pton(AF_INET6, "fd17:625c:f037:0::3", &slirpCfg.vnameserver6);
1707 slirpCfg.vprefix_len = 64;
1708
1709 /* Copy the middle of the IPv4 addresses to the IPv6 addresses. */
1710 slirpCfg.vprefix_addr6.s6_addr[6] = RT_BYTE2(vhost.s_addr);
1711 slirpCfg.vprefix_addr6.s6_addr[7] = RT_BYTE3(vhost.s_addr);
1712 slirpCfg.vhost6.s6_addr[6] = RT_BYTE2(vhost.s_addr);
1713 slirpCfg.vhost6.s6_addr[7] = RT_BYTE3(vhost.s_addr);
1714 slirpCfg.vnameserver6.s6_addr[6] = RT_BYTE2(vnameserver.s_addr);
1715 slirpCfg.vnameserver6.s6_addr[7] = RT_BYTE3(vnameserver.s_addr);
1716
1717 slirpCfg.vhostname = "vbox";
1718 slirpCfg.tftp_server_name = pThis->pszNextServer;
1719 slirpCfg.tftp_path = pThis->pszTFTPPrefix;
1720 slirpCfg.bootfile = pThis->pszBootFile;
1721 slirpCfg.vdhcp_start = vdhcp_start;
1722 slirpCfg.vnameserver = vnameserver;
1723 slirpCfg.if_mtu = MTU;
1724
1725 slirpCfg.vdnssearch = NULL;
1726 slirpCfg.vdomainname = NULL;
1727 slirpCfg.disable_host_loopback = !fLocalhostReachable;
1728 slirpCfg.fForwardBroadcast = fForwardBroadcast;
1729 slirpCfg.iSoMaxConn = i32SoMaxConn;
1730
1731 slirpCallbacks.send_packet = drvNAT_SendPacketCb;
1732 slirpCallbacks.guest_error = drvNAT_GuestErrorCb;
1733 slirpCallbacks.clock_get_ns = drvNAT_ClockGetNsCb;
1734 slirpCallbacks.timer_new = drvNAT_TimerNewCb;
1735 slirpCallbacks.timer_free = drvNAT_TimerFreeCb;
1736 slirpCallbacks.timer_mod = drvNAT_TimerModCb;
1737 slirpCallbacks.notify = drvNAT_NotifyCb;
1738 slirpCallbacks.init_completed = NULL;
1739 slirpCallbacks.timer_new_opaque = NULL;
1740 slirpCallbacks.register_poll_socket = drvNAT_RegisterPoll;
1741 slirpCallbacks.unregister_poll_socket = drvNAT_UnregisterPoll;
1742
1743 /*
1744 * Initialize Slirp
1745 */
1746 Slirp * const pSlirp = slirp_new(/* cfg */ &slirpCfg, /* callbacks */ &slirpCallbacks, /* opaque */ pThis);
1747 if (!pSlirp)
1748 return PDMDRV_SET_ERROR(pDrvIns, VERR_INTERNAL_ERROR_4,
1749 N_("Configuration error: libslirp failed to create new instance - probably misconfiguration"));
1750
1751 pNATState->pSlirp = pSlirp;
1752
1753 rc = drvNATConstructRedir(pDrvIns->iInstance, pThis, pCfg, &Network);
1754 AssertLogRelRCReturn(rc, rc);
1755
1756 rc = PDMDrvHlpSSMRegisterLoadDone(pDrvIns, NULL);
1757 AssertLogRelRCReturn(rc, rc);
1758
1759 rc = RTReqQueueCreate(&pThis->hSlirpReqQueue);
1760 AssertLogRelRCReturn(rc, rc);
1761
1762 rc = RTReqQueueCreate(&pThis->hRecvReqQueue);
1763 AssertLogRelRCReturn(rc, rc);
1764
1765 rc = PDMDrvHlpThreadCreate(pDrvIns, &pThis->pRecvThread, pThis, drvNATRecv,
1766 drvNATRecvWakeup, 256 * _1K, RTTHREADTYPE_IO, "NATRX");
1767 AssertRCReturn(rc, rc);
1768
1769 rc = RTSemEventCreate(&pThis->hEventRecv);
1770 AssertRCReturn(rc, rc);
1771
1772 rc = RTCritSectInit(&pThis->DevAccessLock);
1773 AssertRCReturn(rc, rc);
1774
1775 rc = RTCritSectInit(&pThis->XmitLock);
1776 AssertRCReturn(rc, rc);
1777
1778 char szTmp[128];
1779 RTStrPrintf(szTmp, sizeof(szTmp), "nat%d", pDrvIns->iInstance);
1780 PDMDrvHlpDBGFInfoRegister(pDrvIns, szTmp, "NAT info.", drvNATInfo);
1781
1782#ifdef VBOX_WITH_STATISTICS
1783# define DRV_PROFILE_COUNTER(name, dsc) REGISTER_COUNTER(name, pThis, STAMTYPE_PROFILE, STAMUNIT_TICKS_PER_CALL, dsc)
1784# define DRV_COUNTING_COUNTER(name, dsc) REGISTER_COUNTER(name, pThis, STAMTYPE_COUNTER, STAMUNIT_COUNT, dsc)
1785# include "slirp/counters.h"
1786#endif
1787
1788#ifdef RT_OS_WINDOWS
1789 /* Create the wakeup socket pair (idx=0 is write, idx=1 is read). */
1790 pThis->ahWakeupSockPair[0] = INVALID_SOCKET;
1791 pThis->ahWakeupSockPair[1] = INVALID_SOCKET;
1792 rc = RTWinSocketPair(AF_INET, SOCK_DGRAM, 0, pThis->ahWakeupSockPair);
1793 AssertRCReturn(rc, rc);
1794#else
1795 /* Create the control pipe. */
1796 rc = RTPipeCreate(&pThis->hPipeRead, &pThis->hPipeWrite, 0 /*fFlags*/);
1797 AssertRCReturn(rc, rc);
1798#endif
1799 /* initalize the notifier counter */
1800 pThis->cbWakeupNotifs = 0;
1801
1802 rc = PDMDrvHlpThreadCreate(pDrvIns, &pThis->pSlirpThread, pThis, drvNATAsyncIoThread,
1803 drvNATAsyncIoWakeup, 256 * _1K, RTTHREADTYPE_IO, "NAT");
1804 AssertRCReturn(rc, rc);
1805
1806 pThis->enmLinkState = pThis->enmLinkStateWant = PDMNETWORKLINKSTATE_UP;
1807
1808 return rc;
1809}
1810
1811/**
1812 * NAT network transport driver registration record.
1813 */
1814const PDMDRVREG g_DrvNATlibslirp =
1815{
1816 /* u32Version */
1817 PDM_DRVREG_VERSION,
1818 /* szName */
1819 "NAT",
1820 /* szRCMod */
1821 "",
1822 /* szR0Mod */
1823 "",
1824 /* pszDescription */
1825 "NATlibslrip Network Transport Driver",
1826 /* fFlags */
1827 PDM_DRVREG_FLAGS_HOST_BITS_DEFAULT,
1828 /* fClass. */
1829 PDM_DRVREG_CLASS_NETWORK,
1830 /* cMaxInstances */
1831 ~0U,
1832 /* cbInstance */
1833 sizeof(DRVNAT),
1834 /* pfnConstruct */
1835 drvNATConstruct,
1836 /* pfnDestruct */
1837 drvNATDestruct,
1838 /* pfnRelocate */
1839 NULL,
1840 /* pfnIOCtl */
1841 NULL,
1842 /* pfnPowerOn */
1843 NULL,
1844 /* pfnReset */
1845 NULL,
1846 /* pfnSuspend */
1847 NULL,
1848 /* pfnResume */
1849 NULL,
1850 /* pfnAttach */
1851 NULL,
1852 /* pfnDetach */
1853 NULL,
1854 /* pfnPowerOff */
1855 NULL,
1856 /* pfnSoftReset */
1857 NULL,
1858 /* u32EndVersion */
1859 PDM_DRVREG_VERSION
1860};
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