VirtualBox

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

Last change on this file since 107830 was 107830, checked in by vboxsync, 4 weeks ago

DrvNAT-libslirp: Some more cleanups & fixes (drvNAT_TimerFreeCb, ++). Using the approprate prefixes for timeouts and(/or) documenting the unit really helps with readability. Converted a bunch of unnecessary 'opaque' parameters for internal functions (drvNAT_CheckTimeout, drvNAT_UpdateTimeout, ++) Left a few todos behind. bugref:10268

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

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