VirtualBox

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

最後變更 在這個檔案從107702是 107702,由 vboxsync 提交於 2 月 前

Devices/Network: Parfait fixes. Mostly signedness and precission fixes. Removed unused variables. bugref:3409

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

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