VirtualBox

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

Last change on this file since 107044 was 107028, checked in by vboxsync, 3 months ago

NAT: Consistently take network config from CFGM, and apply part of the IPv4 network address to the IPv6 prefix as well.

  • Property svn:eol-style set to native
  • Property svn:keywords set to Author Date Id Revision
File size: 60.8 KB
Line 
1/* $Id: DrvNATlibslirp.cpp 107028 2024-11-18 14:52:36Z 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 <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
95#define GET_EXTRADATA(pdrvins, node, name, rc, type, type_name, var) \
96 do { \
97 (rc) = (pdrvins)->pHlpR3->pfnCFGMQuery ## type((node), name, &(var)); \
98 if (RT_FAILURE((rc)) && (rc) != VERR_CFGM_VALUE_NOT_FOUND) \
99 return PDMDrvHlpVMSetError((pdrvins), (rc), RT_SRC_POS, \
100 N_("NAT#%d: configuration query for \"" name "\" " #type_name " failed"), \
101 (pdrvins)->iInstance); \
102 } while (0)
103
104#define GET_ED_STRICT(pdrvins, node, name, rc, type, type_name, var) \
105 do { \
106 (rc) = (pdrvins)->pHlpR3->pfnCFGMQuery ## type((node), name, &(var)); \
107 if (RT_FAILURE((rc))) \
108 return PDMDrvHlpVMSetError((pdrvins), (rc), RT_SRC_POS, \
109 N_("NAT#%d: configuration query for \"" name "\" " #type_name " failed"), \
110 (pdrvins)->iInstance); \
111 } while (0)
112
113#define GET_EXTRADATA_N(pdrvins, node, name, rc, type, type_name, var, var_size) \
114 do { \
115 (rc) = (pdrvins)->pHlpR3->pfnCFGMQuery ## type((node), name, &(var), var_size); \
116 if (RT_FAILURE((rc)) && (rc) != VERR_CFGM_VALUE_NOT_FOUND) \
117 return PDMDrvHlpVMSetError((pdrvins), (rc), RT_SRC_POS, \
118 N_("NAT#%d: configuration query for \"" name "\" " #type_name " failed"), \
119 (pdrvins)->iInstance); \
120 } while (0)
121
122#define GET_BOOL(rc, pdrvins, node, name, var) \
123 GET_EXTRADATA(pdrvins, node, name, (rc), Bool, bolean, (var))
124#define GET_STRING(rc, pdrvins, node, name, var, var_size) \
125 GET_EXTRADATA_N(pdrvins, node, name, (rc), String, string, (var), (var_size))
126#define GET_STRING_ALLOC(rc, pdrvins, node, name, var) \
127 GET_EXTRADATA(pdrvins, node, name, (rc), StringAlloc, string, (var))
128#define GET_S32(rc, pdrvins, node, name, var) \
129 GET_EXTRADATA(pdrvins, node, name, (rc), S32, int, (var))
130#define GET_S32_STRICT(rc, pdrvins, node, name, var) \
131 GET_ED_STRICT(pdrvins, node, name, (rc), S32, int, (var))
132
133#define DO_GET_IP(rc, node, instance, status, x) \
134 do { \
135 char sz##x[32]; \
136 GET_STRING((rc), (node), (instance), #x, sz ## x[0], sizeof(sz ## x)); \
137 if (rc != VERR_CFGM_VALUE_NOT_FOUND) \
138 (status) = inet_aton(sz ## x, &x); \
139 } while (0)
140
141#define GETIP_DEF(rc, node, instance, x, def) \
142 do \
143 { \
144 int status = 0; \
145 DO_GET_IP((rc), (node), (instance), status, x); \
146 if (status == 0 || rc == VERR_CFGM_VALUE_NOT_FOUND) \
147 x.s_addr = def; \
148 } while (0)
149
150
151/*********************************************************************************************************************************
152* Structures and Typedefs *
153*********************************************************************************************************************************/
154/** Slirp Timer */
155typedef struct slirpTimer
156{
157 struct slirpTimer *next;
158 uint32_t uTimeExpire;
159 SlirpTimerCb pHandler;
160 void *opaque;
161} SlirpTimer;
162
163/**
164 * Main state of Libslirp NAT
165 */
166typedef struct SlirpState
167{
168 unsigned int nsock;
169
170 Slirp *pSlirp;
171 struct pollfd *polls;
172
173 /** Num Polls (not bytes) */
174 unsigned int uPollCap = 0;
175
176 SlirpTimer *pTimerHead;
177} SlirpState;
178typedef SlirpState *pSlirpState;
179
180/**
181 * NAT network transport driver instance data.
182 *
183 * @implements PDMINETWORKUP
184 */
185typedef struct DRVNAT
186{
187 /** The network interface. */
188 PDMINETWORKUP INetworkUp;
189 /** The network NAT Engine configuration. */
190 PDMINETWORKNATCONFIG INetworkNATCfg;
191 /** The port we're attached to. */
192 PPDMINETWORKDOWN pIAboveNet;
193 /** The network config of the port we're attached to. */
194 PPDMINETWORKCONFIG pIAboveConfig;
195 /** Pointer to the driver instance. */
196 PPDMDRVINS pDrvIns;
197 /** Link state */
198 PDMNETWORKLINKSTATE enmLinkState;
199 /** NAT state */
200 pSlirpState pNATState;
201 /** TFTP directory prefix. */
202 char *pszTFTPPrefix;
203 /** Boot file name to provide in the DHCP server response. */
204 char *pszBootFile;
205 /** tftp server name to provide in the DHCP server response. */
206 char *pszNextServer;
207 /** Polling thread. */
208 PPDMTHREAD pSlirpThread;
209 /** Queue for NAT-thread-external events. */
210 RTREQQUEUE hSlirpReqQueue;
211 /** The guest IP for port-forwarding. */
212 uint32_t GuestIP;
213 /** Link state set when the VM is suspended. */
214 PDMNETWORKLINKSTATE enmLinkStateWant;
215
216#ifndef RT_OS_WINDOWS
217 /** The write end of the control pipe. */
218 RTPIPE hPipeWrite;
219 /** The read end of the control pipe. */
220 RTPIPE hPipeRead;
221#else
222 /* wakeup socket pair for NAT thread */
223 SOCKET pWakeupSockPair[2];
224#endif
225 /* count of bytes sent to notify NAT thread */
226 volatile uint64_t cbWakeupNotifs;
227
228#define DRV_PROFILE_COUNTER(name, dsc) STAMPROFILE Stat ## name
229#define DRV_COUNTING_COUNTER(name, dsc) STAMCOUNTER Stat ## name
230#include "slirp/counters.h"
231 /** thread delivering packets for receiving by the guest */
232 PPDMTHREAD pRecvThread;
233 /** event to wakeup the guest receive thread */
234 RTSEMEVENT EventRecv;
235 /** Receive Req queue (deliver packets to the guest) */
236 RTREQQUEUE hRecvReqQueue;
237
238 /** makes access to device func RecvAvail and Recv atomical. */
239 RTCRITSECT DevAccessLock;
240 /** Number of in-flight packets. */
241 volatile uint32_t cPkts;
242
243 /** Transmit lock taken by BeginXmit and released by EndXmit. */
244 RTCRITSECT XmitLock;
245
246#ifdef RT_OS_DARWIN
247 /* Handle of the DNS watcher runloop source. */
248 CFRunLoopSourceRef hRunLoopSrcDnsWatcher;
249#endif
250} DRVNAT;
251AssertCompileMemberAlignment(DRVNAT, StatNATRecvWakeups, 8);
252/** Pointer to the NAT driver instance data. */
253typedef DRVNAT *PDRVNAT;
254
255
256/*********************************************************************************************************************************
257* Internal Functions *
258*********************************************************************************************************************************/
259static void drvNATNotifyNATThread(PDRVNAT pThis, const char *pszWho);
260static void drvNAT_UpdateTimeout(uint32_t *uTimeout, void *opaque);
261static void drvNAT_CheckTimeout(void *opaque);
262static DECLCALLBACK(int) drvNAT_AddPollCb(int iFd, int iEvents, void *opaque);
263static DECLCALLBACK(int64_t) drvNAT_ClockGetNsCb(void *opaque);
264static DECLCALLBACK(int) drvNAT_GetREventsCb(int idx, void *opaque);
265
266
267
268/*
269 * PDM Function Implementations
270 */
271
272/**
273 * @callback_method_impl{FNPDMTHREADDRV}
274 *
275 * Queues guest process received packet. Triggered by drvNATRecvWakeup.
276 */
277static DECLCALLBACK(int) drvNATRecv(PPDMDRVINS pDrvIns, PPDMTHREAD pThread)
278{
279 PDRVNAT pThis = PDMINS_2_DATA(pDrvIns, PDRVNAT);
280
281 if (pThread->enmState == PDMTHREADSTATE_INITIALIZING)
282 return VINF_SUCCESS;
283
284 while (pThread->enmState == PDMTHREADSTATE_RUNNING)
285 {
286 RTReqQueueProcess(pThis->hRecvReqQueue, 0);
287 if (ASMAtomicReadU32(&pThis->cPkts) == 0)
288 RTSemEventWait(pThis->EventRecv, RT_INDEFINITE_WAIT);
289 }
290 return VINF_SUCCESS;
291}
292
293/**
294 * @callback_method_impl{FNPDMTHREADWAKEUPDRV}
295 */
296static DECLCALLBACK(int) drvNATRecvWakeup(PPDMDRVINS pDrvIns, PPDMTHREAD pThread)
297{
298 RT_NOREF(pThread);
299 PDRVNAT pThis = PDMINS_2_DATA(pDrvIns, PDRVNAT);
300 int rc;
301 rc = RTSemEventSignal(pThis->EventRecv);
302
303 STAM_COUNTER_INC(&pThis->StatNATRecvWakeups);
304 return VINF_SUCCESS;
305}
306
307/**
308 * @brief Processes incoming packet (to guest).
309 *
310 * @param pThis Pointer to DRVNAT state for current context.
311 * @param pBuf Pointer to packet buffer.
312 * @param cb Size of packet in buffer.
313 *
314 * @thread NAT
315 */
316static DECLCALLBACK(void) drvNATRecvWorker(PDRVNAT pThis, void *pBuf, size_t cb)
317{
318 int rc;
319 STAM_PROFILE_START(&pThis->StatNATRecv, a);
320
321 rc = RTCritSectEnter(&pThis->DevAccessLock);
322 AssertRC(rc);
323
324 STAM_PROFILE_START(&pThis->StatNATRecvWait, b);
325 rc = pThis->pIAboveNet->pfnWaitReceiveAvail(pThis->pIAboveNet, RT_INDEFINITE_WAIT);
326 STAM_PROFILE_STOP(&pThis->StatNATRecvWait, b);
327
328 if (RT_SUCCESS(rc))
329 {
330 rc = pThis->pIAboveNet->pfnReceive(pThis->pIAboveNet, pBuf, cb);
331 AssertRC(rc);
332 RTMemFree(pBuf);
333 pBuf = NULL;
334 }
335 else if ( rc != VERR_TIMEOUT
336 && rc != VERR_INTERRUPTED)
337 {
338 AssertRC(rc);
339 }
340
341 rc = RTCritSectLeave(&pThis->DevAccessLock);
342 AssertRC(rc);
343 ASMAtomicDecU32(&pThis->cPkts);
344 drvNATNotifyNATThread(pThis, "drvNATRecvWorker");
345 STAM_PROFILE_STOP(&pThis->StatNATRecv, a);
346}
347
348/**
349 * Frees a S/G buffer allocated by drvNATNetworkUp_AllocBuf.
350 *
351 * @param pThis Pointer to the NAT instance.
352 * @param pSgBuf The S/G buffer to free.
353 *
354 * @thread NAT
355 */
356static void drvNATFreeSgBuf(PDRVNAT pThis, PPDMSCATTERGATHER pSgBuf)
357{
358 RT_NOREF(pThis);
359 Assert((pSgBuf->fFlags & PDMSCATTERGATHER_FLAGS_MAGIC_MASK) == PDMSCATTERGATHER_FLAGS_MAGIC);
360 pSgBuf->fFlags = 0;
361 if (pSgBuf->pvAllocator)
362 {
363 Assert(!pSgBuf->pvUser);
364 RTMemFree(pSgBuf->aSegs[0].pvSeg);
365 }
366 else if (pSgBuf->pvUser)
367 {
368 RTMemFree(pSgBuf->aSegs[0].pvSeg);
369 pSgBuf->aSegs[0].pvSeg = NULL;
370 RTMemFree(pSgBuf->pvUser);
371 pSgBuf->pvUser = NULL;
372 }
373 RTMemFree(pSgBuf);
374}
375
376/**
377 * Worker function for drvNATSend().
378 *
379 * @param pThis Pointer to the NAT instance.
380 * @param pSgBuf The scatter/gather buffer.
381 * @thread NAT
382 */
383static DECLCALLBACK(void) drvNATSendWorker(PDRVNAT pThis, PPDMSCATTERGATHER pSgBuf)
384{
385 LogFlowFunc(("pThis=%p pSgBuf=%p\n", pThis, pSgBuf));
386
387 if (pThis->enmLinkState == PDMNETWORKLINKSTATE_UP)
388 {
389 const uint8_t *m = static_cast<const uint8_t*>(pSgBuf->pvAllocator);
390 if (m)
391 {
392 /*
393 * A normal frame.
394 */
395 LogFlowFunc(("m=%p\n", m));
396 slirp_input(pThis->pNATState->pSlirp, (uint8_t const *)pSgBuf->pvAllocator, (int)pSgBuf->cbUsed);
397 }
398 else
399 {
400 /*
401 * M_EXT buf, need to segment it.
402 */
403
404 uint8_t const *pbFrame = (uint8_t const *)pSgBuf->aSegs[0].pvSeg;
405 PCPDMNETWORKGSO pGso = (PCPDMNETWORKGSO)pSgBuf->pvUser;
406 /* Do not attempt to segment frames with invalid GSO parameters. */
407 if (PDMNetGsoIsValid((const PDMNETWORKGSO *)pGso, sizeof(*pGso), pSgBuf->cbUsed))
408 {
409 uint32_t const cSegs = PDMNetGsoCalcSegmentCount(pGso, pSgBuf->cbUsed);
410 Assert(cSegs > 1);
411 for (uint32_t iSeg = 0; iSeg < cSegs; iSeg++)
412 {
413 void *pvSeg;
414 pvSeg = RTMemAlloc(DRVNAT_MAXFRAMESIZE);
415
416 uint32_t cbPayload, cbHdrs;
417 uint32_t offPayload = PDMNetGsoCarveSegment(pGso, pbFrame, pSgBuf->cbUsed,
418 iSeg, cSegs, (uint8_t *)pvSeg, &cbHdrs, &cbPayload);
419 memcpy((uint8_t *)pvSeg + cbHdrs, pbFrame + offPayload, cbPayload);
420
421 slirp_input(pThis->pNATState->pSlirp, (uint8_t const *)pvSeg, cbPayload + cbHdrs);
422 RTMemFree(pvSeg);
423 }
424 }
425 }
426 }
427
428 LogFlowFunc(("leave\n"));
429 drvNATFreeSgBuf(pThis, pSgBuf);
430}
431
432/**
433 * @interface_method_impl{PDMINETWORKUP,pfnBeginXmit}
434 */
435static DECLCALLBACK(int) drvNATNetworkUp_BeginXmit(PPDMINETWORKUP pInterface, bool fOnWorkerThread)
436{
437 RT_NOREF(fOnWorkerThread);
438 PDRVNAT pThis = RT_FROM_MEMBER(pInterface, DRVNAT, INetworkUp);
439 int rc = RTCritSectTryEnter(&pThis->XmitLock);
440 if (RT_FAILURE(rc))
441 {
442 /** @todo Kick the worker thread when we have one... */
443 rc = VERR_TRY_AGAIN;
444 }
445 LogFlowFunc(("Beginning xmit...\n"));
446 return rc;
447}
448
449/**
450 * @interface_method_impl{PDMINETWORKUP,pfnAllocBuf}
451 */
452static DECLCALLBACK(int) drvNATNetworkUp_AllocBuf(PPDMINETWORKUP pInterface, size_t cbMin,
453 PCPDMNETWORKGSO pGso, PPPDMSCATTERGATHER ppSgBuf)
454{
455 PDRVNAT pThis = RT_FROM_MEMBER(pInterface, DRVNAT, INetworkUp);
456 Assert(RTCritSectIsOwner(&pThis->XmitLock));
457
458 LogFlowFuncEnter();
459
460 /*
461 * Drop the incoming frame if the NAT thread isn't running.
462 */
463 if (pThis->pSlirpThread->enmState != PDMTHREADSTATE_RUNNING)
464 {
465 Log(("drvNATNetowrkUp_AllocBuf: returns VERR_NET_DOWN\n"));
466 return VERR_NET_DOWN;
467 }
468
469 /*
470 * Allocate a scatter/gather buffer and an mbuf.
471 */
472 PPDMSCATTERGATHER pSgBuf = (PPDMSCATTERGATHER)RTMemAllocZ(sizeof(PDMSCATTERGATHER));
473 if (!pSgBuf)
474 return VERR_NO_MEMORY;
475 if (!pGso)
476 {
477 /*
478 * Drop the frame if it is too big.
479 */
480 if (cbMin >= DRVNAT_MAXFRAMESIZE)
481 {
482 Log(("drvNATNetowrkUp_AllocBuf: drops over-sized frame (%u bytes), returns VERR_INVALID_PARAMETER\n",
483 cbMin));
484 RTMemFree(pSgBuf);
485 return VERR_INVALID_PARAMETER;
486 }
487
488 pSgBuf->pvUser = NULL;
489 pSgBuf->aSegs[0].cbSeg = RT_ALIGN_Z(cbMin, 128);
490 pSgBuf->aSegs[0].pvSeg = RTMemAlloc(pSgBuf->aSegs[0].cbSeg);
491 pSgBuf->pvAllocator = pSgBuf->aSegs[0].pvSeg;
492
493 if (!pSgBuf->pvAllocator)
494 {
495 RTMemFree(pSgBuf);
496 return VERR_TRY_AGAIN;
497 }
498 }
499 else
500 {
501 /*
502 * Drop the frame if its segment is too big.
503 */
504 if (pGso->cbHdrsTotal + pGso->cbMaxSeg >= DRVNAT_MAXFRAMESIZE)
505 {
506 Log(("drvNATNetowrkUp_AllocBuf: drops over-sized frame (%u bytes), returns VERR_INVALID_PARAMETER\n",
507 pGso->cbHdrsTotal + pGso->cbMaxSeg));
508 RTMemFree(pSgBuf);
509 return VERR_INVALID_PARAMETER;
510 }
511
512 pSgBuf->pvUser = RTMemDup(pGso, sizeof(*pGso));
513 pSgBuf->pvAllocator = NULL;
514
515 pSgBuf->aSegs[0].cbSeg = RT_ALIGN_Z(cbMin, 128);
516 pSgBuf->aSegs[0].pvSeg = RTMemAlloc(pSgBuf->aSegs[0].cbSeg);
517 if (!pSgBuf->pvUser || !pSgBuf->aSegs[0].pvSeg)
518 {
519 RTMemFree(pSgBuf->aSegs[0].pvSeg);
520 RTMemFree(pSgBuf->pvUser);
521 RTMemFree(pSgBuf);
522 return VERR_TRY_AGAIN;
523 }
524 }
525
526 /*
527 * Initialize the S/G buffer and return.
528 */
529 pSgBuf->fFlags = PDMSCATTERGATHER_FLAGS_MAGIC | PDMSCATTERGATHER_FLAGS_OWNER_1;
530 pSgBuf->cbUsed = 0;
531 pSgBuf->cbAvailable = pSgBuf->aSegs[0].cbSeg;
532 pSgBuf->cSegs = 1;
533
534 *ppSgBuf = pSgBuf;
535 return VINF_SUCCESS;
536}
537
538/**
539 * @interface_method_impl{PDMINETWORKUP,pfnFreeBuf}
540 */
541static DECLCALLBACK(int) drvNATNetworkUp_FreeBuf(PPDMINETWORKUP pInterface, PPDMSCATTERGATHER pSgBuf)
542{
543 PDRVNAT pThis = RT_FROM_MEMBER(pInterface, DRVNAT, INetworkUp);
544 Assert(RTCritSectIsOwner(&pThis->XmitLock));
545 drvNATFreeSgBuf(pThis, pSgBuf);
546 return VINF_SUCCESS;
547}
548
549/**
550 * @interface_method_impl{PDMINETWORKUP,pfnSendBuf}
551 */
552static DECLCALLBACK(int) drvNATNetworkUp_SendBuf(PPDMINETWORKUP pInterface, PPDMSCATTERGATHER pSgBuf, bool fOnWorkerThread)
553{
554 RT_NOREF(fOnWorkerThread);
555 PDRVNAT pThis = RT_FROM_MEMBER(pInterface, DRVNAT, INetworkUp);
556 Assert((pSgBuf->fFlags & PDMSCATTERGATHER_FLAGS_OWNER_MASK) == PDMSCATTERGATHER_FLAGS_OWNER_1);
557 Assert(RTCritSectIsOwner(&pThis->XmitLock));
558
559 LogFlowFunc(("enter\n"));
560
561 int rc;
562 if (pThis->pSlirpThread->enmState == PDMTHREADSTATE_RUNNING)
563 {
564 rc = RTReqQueueCallEx(pThis->hSlirpReqQueue, NULL /*ppReq*/, 0 /*cMillies*/, RTREQFLAGS_VOID | RTREQFLAGS_NO_WAIT,
565 (PFNRT)drvNATSendWorker, 2, pThis, pSgBuf);
566 if (RT_SUCCESS(rc))
567 {
568 drvNATNotifyNATThread(pThis, "drvNATNetworkUp_SendBuf");
569 LogFlowFunc(("leave success\n"));
570 return VINF_SUCCESS;
571 }
572
573 rc = VERR_NET_NO_BUFFER_SPACE;
574 }
575 else
576 rc = VERR_NET_DOWN;
577 drvNATFreeSgBuf(pThis, pSgBuf);
578 LogFlowFunc(("leave rc=%Rrc\n", rc));
579 return rc;
580}
581
582/**
583 * @interface_method_impl{PDMINETWORKUP,pfnEndXmit}
584 */
585static DECLCALLBACK(void) drvNATNetworkUp_EndXmit(PPDMINETWORKUP pInterface)
586{
587 PDRVNAT pThis = RT_FROM_MEMBER(pInterface, DRVNAT, INetworkUp);
588 RTCritSectLeave(&pThis->XmitLock);
589}
590
591/**
592 * Get the NAT thread out of poll/WSAWaitForMultipleEvents
593 */
594static void drvNATNotifyNATThread(PDRVNAT pThis, const char *pszWho)
595{
596 RT_NOREF(pszWho);
597 int rc = 0;
598#ifndef RT_OS_WINDOWS
599 /* kick poll() */
600 size_t cbIgnored;
601 rc = RTPipeWrite(pThis->hPipeWrite, "", 1, &cbIgnored);
602 if (RT_SUCCESS(rc))
603 {
604 /* Count how many bites we send down the socket */
605 ASMAtomicIncU64(&pThis->cbWakeupNotifs);
606 }
607#else
608 int cbWritten = send(pThis->pWakeupSockPair[0], "", 1, NULL);
609 if (cbWritten == SOCKET_ERROR)
610 {
611 Log4(("Notify NAT Thread Error %d\n", WSAGetLastError()));
612 }
613 else
614 {
615 /* Count how many bites we send down the socket */
616 ASMAtomicIncU64(&pThis->cbWakeupNotifs);
617 }
618#endif
619 AssertRC(rc);
620}
621
622/**
623 * @interface_method_impl{PDMINETWORKUP,pfnSetPromiscuousMode}
624 */
625static DECLCALLBACK(void) drvNATNetworkUp_SetPromiscuousMode(PPDMINETWORKUP pInterface, bool fPromiscuous)
626{
627 RT_NOREF(pInterface, fPromiscuous);
628 LogFlow(("drvNATNetworkUp_SetPromiscuousMode: fPromiscuous=%d\n", fPromiscuous));
629 /* nothing to do */
630}
631
632/**
633 * Worker function for drvNATNetworkUp_NotifyLinkChanged().
634 * @thread "NAT" thread.
635 *
636 * @param pThis Pointer to DRVNAT state for current context.
637 * @param enmLinkState Enum value of link state.
638 *
639 * @thread NAT
640 */
641static DECLCALLBACK(void) drvNATNotifyLinkChangedWorker(PDRVNAT pThis, PDMNETWORKLINKSTATE enmLinkState)
642{
643 pThis->enmLinkState = pThis->enmLinkStateWant = enmLinkState;
644 switch (enmLinkState)
645 {
646 case PDMNETWORKLINKSTATE_UP:
647 LogRel(("NAT: Link up\n"));
648 break;
649
650 case PDMNETWORKLINKSTATE_DOWN:
651 case PDMNETWORKLINKSTATE_DOWN_RESUME:
652 LogRel(("NAT: Link down\n"));
653 break;
654
655 default:
656 AssertMsgFailed(("drvNATNetworkUp_NotifyLinkChanged: unexpected link state %d\n", enmLinkState));
657 }
658}
659
660/**
661 * Notification on link status changes.
662 *
663 * @param pInterface Pointer to the interface structure containing the called function pointer.
664 * @param enmLinkState The new link state.
665 *
666 * @thread EMT
667 */
668static DECLCALLBACK(void) drvNATNetworkUp_NotifyLinkChanged(PPDMINETWORKUP pInterface, PDMNETWORKLINKSTATE enmLinkState)
669{
670 PDRVNAT pThis = RT_FROM_MEMBER(pInterface, DRVNAT, INetworkUp);
671
672 LogFlow(("drvNATNetworkUp_NotifyLinkChanged: enmLinkState=%d\n", enmLinkState));
673
674 /* Don't queue new requests if the NAT thread is not running (e.g. paused,
675 * stopping), otherwise we would deadlock. Memorize the change. */
676 if (pThis->pSlirpThread->enmState != PDMTHREADSTATE_RUNNING)
677 {
678 pThis->enmLinkStateWant = enmLinkState;
679 return;
680 }
681
682 PRTREQ pReq;
683 int rc = RTReqQueueCallEx(pThis->hSlirpReqQueue, &pReq, 0 /*cMillies*/, RTREQFLAGS_VOID,
684 (PFNRT)drvNATNotifyLinkChangedWorker, 2, pThis, enmLinkState);
685 if (rc == VERR_TIMEOUT)
686 {
687 drvNATNotifyNATThread(pThis, "drvNATNetworkUp_NotifyLinkChanged");
688 rc = RTReqWait(pReq, RT_INDEFINITE_WAIT);
689 AssertRC(rc);
690 }
691 else
692 AssertRC(rc);
693 RTReqRelease(pReq);
694}
695
696/**
697 * NAT thread handling the slirp stuff.
698 *
699 * The slirp implementation is single-threaded so we execute this enginre in a
700 * dedicated thread. We take care that this thread does not become the
701 * bottleneck: If the guest wants to send, a request is enqueued into the
702 * hSlirpReqQueue and handled asynchronously by this thread. If this thread
703 * wants to deliver packets to the guest, it enqueues a request into
704 * hRecvReqQueue which is later handled by the Recv thread.
705 *
706 * @param pDrvIns Pointer to PDM driver context.
707 * @param pThread Pointer to calling thread context.
708 *
709 * @returns VBox status code
710 *
711 * @thread NAT
712 */
713static DECLCALLBACK(int) drvNATAsyncIoThread(PPDMDRVINS pDrvIns, PPDMTHREAD pThread)
714{
715 PDRVNAT pThis = PDMINS_2_DATA(pDrvIns, PDRVNAT);
716#ifdef RT_OS_WINDOWS
717 drvNAT_AddPollCb(pThis->pWakeupSockPair[1], SLIRP_POLL_IN | SLIRP_POLL_HUP, pThis);
718 pThis->pNATState->polls[0].fd = pThis->pWakeupSockPair[1];
719#else
720 unsigned int cPollNegRet = 0;
721 drvNAT_AddPollCb(RTPipeToNative(pThis->hPipeRead), SLIRP_POLL_IN | SLIRP_POLL_HUP, pThis);
722 pThis->pNATState->polls[0].fd = RTPipeToNative(pThis->hPipeRead);
723 pThis->pNATState->polls[0].events = POLLRDNORM | POLLPRI | POLLRDBAND;
724 pThis->pNATState->polls[0].revents = 0;
725#endif /* !RT_OS_WINDOWS */
726
727 LogFlow(("drvNATAsyncIoThread: pThis=%p\n", pThis));
728
729 if (pThread->enmState == PDMTHREADSTATE_INITIALIZING)
730 return VINF_SUCCESS;
731
732 if (pThis->enmLinkStateWant != pThis->enmLinkState)
733 drvNATNotifyLinkChangedWorker(pThis, pThis->enmLinkStateWant);
734
735 /*
736 * Polling loop.
737 */
738 while (pThread->enmState == PDMTHREADSTATE_RUNNING)
739 {
740 /*
741 * To prevent concurrent execution of sending/receiving threads
742 */
743#ifndef RT_OS_WINDOWS
744 uint32_t uTimeout = DRVNAT_DEFAULT_TIMEOUT;
745 pThis->pNATState->nsock = 1;
746
747 slirp_pollfds_fill(pThis->pNATState->pSlirp, &uTimeout, drvNAT_AddPollCb /* SlirpAddPollCb */, pThis /* opaque */);
748 drvNAT_UpdateTimeout(&uTimeout, pThis);
749
750 int cChangedFDs = poll(pThis->pNATState->polls, pThis->pNATState->nsock, uTimeout /* timeout */);
751
752 if (cChangedFDs < 0)
753 {
754 if (errno == EINTR)
755 {
756 Log2(("NAT: signal was caught while sleep on poll\n"));
757 /* No error, just process all outstanding requests but don't wait */
758 cChangedFDs = 0;
759 }
760 else if (cPollNegRet++ > 128)
761 {
762 LogRel(("NAT: Poll returns (%s) suppressed %d\n", strerror(errno), cPollNegRet));
763 cPollNegRet = 0;
764 }
765 }
766
767
768 slirp_pollfds_poll(pThis->pNATState->pSlirp, cChangedFDs < 0, drvNAT_GetREventsCb /* SlirpGetREventsCb */, pThis /* opaque */);
769 if (pThis->pNATState->polls[0].revents & (POLLRDNORM|POLLPRI|POLLRDBAND))
770 {
771 /* drain the pipe
772 *
773 * Note! drvNATSend decoupled so we don't know how many times
774 * device's thread sends before we've entered multiplex,
775 * so to avoid false alarm drain pipe here to the very end
776 */
777 char ch[1024];
778 size_t cbRead;
779 uint64_t cbWakeupNotifs = ASMAtomicReadU64(&pThis->cbWakeupNotifs);
780 RTPipeRead(pThis->hPipeRead, &ch[0], RT_MIN(cbWakeupNotifs, 1024), &cbRead);
781 ASMAtomicSubU64(&pThis->cbWakeupNotifs, cbRead);
782 }
783
784 /* process _all_ outstanding requests but don't wait */
785 RTReqQueueProcess(pThis->hSlirpReqQueue, 0);
786 drvNAT_CheckTimeout(pThis);
787
788#else /* RT_OS_WINDOWS */
789 uint32_t msTimeout = DRVNAT_DEFAULT_TIMEOUT;
790 pThis->pNATState->nsock = 1;
791 slirp_pollfds_fill(pThis->pNATState->pSlirp, &msTimeout, drvNAT_AddPollCb /* SlirpAddPollCb */, pThis /* opaque */);
792 drvNAT_UpdateTimeout(&msTimeout, pThis);
793
794 int cChangedFDs = WSAPoll(pThis->pNATState->polls, pThis->pNATState->nsock, msTimeout /* timeout */);
795 int error = WSAGetLastError();
796 if (cChangedFDs == SOCKET_ERROR)
797 {
798 LogRel(("NAT: RTWinPoll returned error=%Rrc (cChangedFDs=%d)\n", error, cChangedFDs));
799 Log4(("NAT: NSOCK = %d\n", pThis->pNATState->nsock));
800 }
801
802 if (pThis->pNATState->polls[0].revents & (POLLIN))
803 {
804 /* drain the pipe
805 *
806 * Note! drvNATSend decoupled so we don't know how many times
807 * device's thread sends before we've entered multiplex,
808 * so to avoid false alarm drain pipe here to the very end
809 */
810 char ch[1024];
811 size_t cbRead;
812 uint64_t cbWakeupNotifs = ASMAtomicReadU64(&pThis->cbWakeupNotifs);
813 cbRead = recv(pThis->pWakeupSockPair[1], &ch[0], RT_MIN(cbWakeupNotifs, 1024), NULL);
814 ASMAtomicSubU64(&pThis->cbWakeupNotifs, cbRead);
815 }
816
817 if (cChangedFDs == 0)
818 {
819 /* only check for slow/fast timers */
820 slirp_pollfds_poll(pThis->pNATState->pSlirp, false /*select error*/, drvNAT_GetREventsCb /* SlirpGetREventsCb */, pThis /* opaque */);
821 RTReqQueueProcess(pThis->hSlirpReqQueue, 0);
822 continue;
823 }
824 /* poll the sockets in any case */
825 Log2(("%s: poll\n", __FUNCTION__));
826 slirp_pollfds_poll(pThis->pNATState->pSlirp, cChangedFDs < 0 /*select error*/, drvNAT_GetREventsCb /* SlirpGetREventsCb */, pThis /* opaque */);
827
828 /* process _all_ outstanding requests but don't wait */
829 RTReqQueueProcess(pThis->hSlirpReqQueue, 0);
830 drvNAT_CheckTimeout(pThis);
831#endif /* RT_OS_WINDOWS */
832 }
833
834 return VINF_SUCCESS;
835}
836
837/**
838 * Unblock the send thread so it can respond to a state change.
839 *
840 * @returns VBox status code.
841 * @param pDrvIns The pcnet device instance.
842 * @param pThread The send thread.
843 *
844 * @thread ?
845 */
846static DECLCALLBACK(int) drvNATAsyncIoWakeup(PPDMDRVINS pDrvIns, PPDMTHREAD pThread)
847{
848 RT_NOREF(pThread);
849 PDRVNAT pThis = PDMINS_2_DATA(pDrvIns, PDRVNAT);
850
851 drvNATNotifyNATThread(pThis, "drvNATAsyncIoWakeup");
852 return VINF_SUCCESS;
853}
854
855/**
856 * @interface_method_impl{PDMIBASE,pfnQueryInterface}
857 */
858static DECLCALLBACK(void *) drvNATQueryInterface(PPDMIBASE pInterface, const char *pszIID)
859{
860 PPDMDRVINS pDrvIns = PDMIBASE_2_PDMDRV(pInterface);
861 PDRVNAT pThis = PDMINS_2_DATA(pDrvIns, PDRVNAT);
862
863 PDMIBASE_RETURN_INTERFACE(pszIID, PDMIBASE, &pDrvIns->IBase);
864 PDMIBASE_RETURN_INTERFACE(pszIID, PDMINETWORKUP, &pThis->INetworkUp);
865 PDMIBASE_RETURN_INTERFACE(pszIID, PDMINETWORKNATCONFIG, &pThis->INetworkNATCfg);
866 return NULL;
867}
868
869/**
870 * Info handler.
871 *
872 * @param pDrvIns The PDM driver context.
873 * @param pHlp ....
874 * @param pszArgs Unused.
875 *
876 * @thread any
877 */
878static DECLCALLBACK(void) drvNATInfo(PPDMDRVINS pDrvIns, PCDBGFINFOHLP pHlp, const char *pszArgs)
879{
880 RT_NOREF(pszArgs);
881 PDRVNAT pThis = PDMINS_2_DATA(pDrvIns, PDRVNAT);
882 pHlp->pfnPrintf(pHlp, "libslirp Connection Info:\n");
883 pHlp->pfnPrintf(pHlp, slirp_connection_info(pThis->pNATState->pSlirp));
884 pHlp->pfnPrintf(pHlp, "libslirp Neighbor Info:\n");
885 pHlp->pfnPrintf(pHlp, slirp_neighbor_info(pThis->pNATState->pSlirp));
886 pHlp->pfnPrintf(pHlp, "libslirp Version String: %s \n", slirp_version_string());
887}
888
889/**
890 * Sets up the redirectors.
891 *
892 * @returns VBox status code.
893 * @param uInstance ?
894 * @param pThis ?
895 * @param pCfg The configuration handle.
896 * @param pNetwork Unused.
897 *
898 * @thread ?
899 */
900static int drvNATConstructRedir(unsigned iInstance, PDRVNAT pThis, PCFGMNODE pCfg, PRTNETADDRIPV4 pNetwork)
901{
902 /** @todo r=jack: rewrite to support IPv6? */
903 PPDMDRVINS pDrvIns = pThis->pDrvIns;
904 PCPDMDRVHLPR3 pHlp = pDrvIns->pHlpR3;
905
906 RT_NOREF(pNetwork); /** @todo figure why pNetwork isn't used */
907
908 PCFGMNODE pPFTree = pHlp->pfnCFGMGetChild(pCfg, "PortForwarding");
909 if (pPFTree == NULL)
910 return VINF_SUCCESS;
911
912 /*
913 * Enumerate redirections.
914 */
915 for (PCFGMNODE pNode = pHlp->pfnCFGMGetFirstChild(pPFTree); pNode; pNode = pHlp->pfnCFGMGetNextChild(pNode))
916 {
917 /*
918 * Validate the port forwarding config.
919 */
920 if (!pHlp->pfnCFGMAreValuesValid(pNode, "Name\0Protocol\0UDP\0HostPort\0GuestPort\0GuestIP\0BindIP\0"))
921 return PDMDRV_SET_ERROR(pDrvIns, VERR_PDM_DRVINS_UNKNOWN_CFG_VALUES,
922 N_("Unknown configuration in port forwarding"));
923
924 /* protocol type */
925 bool fUDP;
926 char szProtocol[32];
927 int rc;
928 GET_STRING(rc, pDrvIns, pNode, "Protocol", szProtocol[0], sizeof(szProtocol));
929 if (rc == VERR_CFGM_VALUE_NOT_FOUND)
930 {
931 fUDP = false;
932 GET_BOOL(rc, pDrvIns, pNode, "UDP", fUDP);
933 }
934 else if (RT_SUCCESS(rc))
935 {
936 if (!RTStrICmp(szProtocol, "TCP"))
937 fUDP = false;
938 else if (!RTStrICmp(szProtocol, "UDP"))
939 fUDP = true;
940 else
941 return PDMDrvHlpVMSetError(pDrvIns, VERR_INVALID_PARAMETER, RT_SRC_POS,
942 N_("NAT#%d: Invalid configuration value for \"Protocol\": \"%s\""),
943 iInstance, szProtocol);
944 }
945 else
946 return PDMDrvHlpVMSetError(pDrvIns, rc, RT_SRC_POS,
947 N_("NAT#%d: configuration query for \"Protocol\" failed"),
948 iInstance);
949 /* host port */
950 int32_t iHostPort;
951 GET_S32_STRICT(rc, pDrvIns, pNode, "HostPort", iHostPort);
952
953 /* guest port */
954 int32_t iGuestPort;
955 GET_S32_STRICT(rc, pDrvIns, pNode, "GuestPort", iGuestPort);
956
957 /* host address ("BindIP" name is rather unfortunate given "HostPort" to go with it) */
958 struct in_addr BindIP;
959 RT_ZERO(BindIP);
960 GETIP_DEF(rc, pDrvIns, pNode, BindIP, INADDR_ANY);
961
962 /* guest address */
963 struct in_addr GuestIP;
964 RT_ZERO(GuestIP);
965 GETIP_DEF(rc, pDrvIns, pNode, GuestIP, INADDR_ANY);
966
967 /*
968 * Call slirp about it.
969 */
970 if (slirp_add_hostfwd(pThis->pNATState->pSlirp, fUDP, BindIP,
971 iHostPort, GuestIP, iGuestPort) < 0)
972 return PDMDrvHlpVMSetError(pThis->pDrvIns, VERR_NAT_REDIR_SETUP, RT_SRC_POS,
973 N_("NAT#%d: configuration error: failed to set up "
974 "redirection of %d to %d. Probably a conflict with "
975 "existing services or other rules"), iInstance, iHostPort,
976 iGuestPort);
977 } /* for each redir rule */
978
979 return VINF_SUCCESS;
980}
981
982/**
983 * Applies port forwarding between guest and host.
984 *
985 * @param pThis Pointer to DRVNAT state for current context.
986 * @param fRemove Flag to remove port forward instead of create.
987 * @param fUdp Flag specifying if UDP. If false, TCP.
988 * @param pHostIp String of host IP address.
989 * @param u16HostPort Host port to forward to.
990 * @param pGuestIp String of guest IP address.
991 * @param u16GuestPort Guest port to forward.
992 *
993 * @thread ?
994 */
995static DECLCALLBACK(void) drvNATNotifyApplyPortForwardCommand(PDRVNAT pThis, bool fRemove,
996 bool fUdp, const char *pHostIp,
997 uint16_t u16HostPort, const char *pGuestIp, uint16_t u16GuestPort)
998{
999 /** @todo r=jack:
1000 * - rewrite for IPv6
1001 * - do we want to lock the guestIp to the VMs IP?
1002 */
1003 struct in_addr guestIp, hostIp;
1004
1005 if ( pHostIp == NULL
1006 || inet_aton(pHostIp, &hostIp) == 0)
1007 hostIp.s_addr = INADDR_ANY;
1008
1009 if ( pGuestIp == NULL
1010 || inet_aton(pGuestIp, &guestIp) == 0)
1011 guestIp.s_addr = pThis->GuestIP;
1012
1013 if (fRemove)
1014 slirp_remove_hostfwd(pThis->pNATState->pSlirp, fUdp, hostIp, u16HostPort);
1015 else
1016 slirp_add_hostfwd(pThis->pNATState->pSlirp, fUdp, hostIp,
1017 u16HostPort, guestIp, u16GuestPort);
1018}
1019
1020/**
1021 * @interface_method_impl{PDMINETWORKNATCONFIG,pfnRedirectRuleCommand}
1022 */
1023static DECLCALLBACK(int) drvNATNetworkNatConfigRedirect(PPDMINETWORKNATCONFIG pInterface, bool fRemove,
1024 bool fUdp, const char *pHostIp, uint16_t u16HostPort,
1025 const char *pGuestIp, uint16_t u16GuestPort)
1026{
1027 LogFlowFunc(("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 {
1034 drvNATNotifyApplyPortForwardCommand(pThis, fRemove, fUdp, pHostIp,
1035 u16HostPort, pGuestIp,u16GuestPort);
1036 rc = VINF_SUCCESS;
1037 }
1038 else
1039 {
1040 PRTREQ pReq;
1041 rc = RTReqQueueCallEx(pThis->hSlirpReqQueue, &pReq, 0 /*cMillies*/, RTREQFLAGS_VOID,
1042 (PFNRT)drvNATNotifyApplyPortForwardCommand, 7, pThis, fRemove,
1043 fUdp, pHostIp, u16HostPort, pGuestIp, u16GuestPort);
1044 if (rc == VERR_TIMEOUT)
1045 {
1046 drvNATNotifyNATThread(pThis, "drvNATNetworkNatConfigRedirect");
1047 rc = RTReqWait(pReq, RT_INDEFINITE_WAIT);
1048 AssertRC(rc);
1049 }
1050 else
1051 AssertRC(rc);
1052
1053 RTReqRelease(pReq);
1054 }
1055 return rc;
1056}
1057
1058/**
1059 * @interface_method_impl{PDMINETWORKNATCONFIG,pfnNotifyDnsChanged}
1060 */
1061static DECLCALLBACK(void) drvNATNotifyDnsChanged(PPDMINETWORKNATCONFIG pInterface, PCPDMINETWORKNATDNSCONFIG pDnsConf)
1062{
1063 PDRVNAT const pThis = RT_FROM_MEMBER(pInterface, DRVNAT, INetworkNATCfg);
1064 SlirpState * const pNATState = pThis->pNATState;
1065 AssertReturnVoid(pNATState);
1066 AssertReturnVoid(pNATState->pSlirp);
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(uint32_t *uTimeout, void *opaque)
1093{
1094 PDRVNAT pThis = (PDRVNAT)opaque;
1095 Assert(pThis);
1096
1097 uint32_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 int drvNAT_PollEventSlirpToHost(int iEvents) {
1156 int 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 int 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 int idx = pThis->pNATState->nsock;
1411#ifdef RT_OS_WINDOWS
1412 pThis->pNATState->polls[idx].fd = libslirp_wrap_RTHandleTableLookup(iFd);
1413#else
1414 pThis->pNATState->polls[idx].fd = iFd;
1415#endif
1416 pThis->pNATState->polls[idx].events = drvNAT_PollEventSlirpToHost(iEvents);
1417 pThis->pNATState->polls[idx].revents = 0;
1418 pThis->pNATState->nsock += 1;
1419 return idx;
1420}
1421
1422/**
1423 * Get translated revents from a poll at a given index.
1424 *
1425 * @param idx Integer index of poll.
1426 * @param opaque Pointer to NAT State context.
1427 *
1428 * @returns Integer representing transalted revents.
1429 *
1430 * @thread ?
1431 */
1432static DECLCALLBACK(int) drvNAT_GetREventsCb(int idx, void *opaque)
1433{
1434 PDRVNAT pThis = (PDRVNAT)opaque;
1435 struct pollfd* polls = pThis->pNATState->polls;
1436 return drvNAT_PollEventHostToSlirp(polls[idx].revents);
1437}
1438
1439/**
1440 * Contructor/Destructor
1441 */
1442/**
1443 * Destruct a driver instance.
1444 *
1445 * Most VM resources are freed by the VM. This callback is provided so that any non-VM
1446 * resources can be freed correctly.
1447 *
1448 * @param pDrvIns The driver instance data.
1449 */
1450static DECLCALLBACK(void) drvNATDestruct(PPDMDRVINS pDrvIns)
1451{
1452 PDRVNAT pThis = PDMINS_2_DATA(pDrvIns, PDRVNAT);
1453 LogFlow(("drvNATDestruct:\n"));
1454 PDMDRV_CHECK_VERSIONS_RETURN_VOID(pDrvIns);
1455
1456 SlirpState * const pNATState = pThis->pNATState;
1457 if (pNATState)
1458 {
1459 slirp_cleanup(pNATState->pSlirp);
1460
1461#ifdef VBOX_WITH_STATISTICS
1462# define DRV_PROFILE_COUNTER(name, dsc) DEREGISTER_COUNTER(name, pThis)
1463# define DRV_COUNTING_COUNTER(name, dsc) DEREGISTER_COUNTER(name, pThis)
1464# include "slirp/counters.h"
1465#endif
1466 RTMemFree(pNATState->polls);
1467 pNATState->polls = NULL;
1468
1469 RTMemFree(pNATState);
1470 pThis->pNATState = NULL;
1471 }
1472
1473 RTReqQueueDestroy(pThis->hSlirpReqQueue);
1474 pThis->hSlirpReqQueue = NIL_RTREQQUEUE;
1475
1476 RTReqQueueDestroy(pThis->hRecvReqQueue);
1477 pThis->hRecvReqQueue = NIL_RTREQQUEUE;
1478
1479 RTSemEventDestroy(pThis->EventRecv);
1480 pThis->EventRecv = NIL_RTSEMEVENT;
1481
1482 if (RTCritSectIsInitialized(&pThis->DevAccessLock))
1483 RTCritSectDelete(&pThis->DevAccessLock);
1484
1485 if (RTCritSectIsInitialized(&pThis->XmitLock))
1486 RTCritSectDelete(&pThis->XmitLock);
1487
1488#ifndef RT_OS_WINDOWS
1489 RTPipeClose(pThis->hPipeRead);
1490 RTPipeClose(pThis->hPipeWrite);
1491#endif
1492}
1493
1494/**
1495 * Construct a NAT network transport driver instance.
1496 *
1497 * @copydoc FNPDMDRVCONSTRUCT
1498 */
1499static DECLCALLBACK(int) drvNATConstruct(PPDMDRVINS pDrvIns, PCFGMNODE pCfg, uint32_t fFlags)
1500{
1501 RT_NOREF(fFlags);
1502 PDMDRV_CHECK_VERSIONS_RETURN(pDrvIns);
1503 PDRVNAT pThis = PDMINS_2_DATA(pDrvIns, PDRVNAT);
1504
1505 /*
1506 * Init the static parts.
1507 */
1508 pThis->pDrvIns = pDrvIns;
1509
1510 SlirpState * const pNATState = (SlirpState *)RTMemAllocZ(sizeof(*pNATState));
1511 if (pNATState == NULL)
1512 return VERR_NO_MEMORY;
1513 pThis->pNATState = pNATState;
1514 pNATState->nsock = 0;
1515 pNATState->pTimerHead = NULL;
1516 pNATState->polls = (struct pollfd *)RTMemAllocZ(64 * sizeof(struct pollfd));
1517 AssertReturn(pNATState->polls, VERR_NO_MEMORY);
1518 pNATState->uPollCap = 64;
1519
1520 pThis->hSlirpReqQueue = NIL_RTREQQUEUE;
1521 pThis->EventRecv = NIL_RTSEMEVENT;
1522
1523 /* IBase */
1524 pDrvIns->IBase.pfnQueryInterface = drvNATQueryInterface;
1525
1526 /* INetwork */
1527 pThis->INetworkUp.pfnBeginXmit = drvNATNetworkUp_BeginXmit;
1528 pThis->INetworkUp.pfnAllocBuf = drvNATNetworkUp_AllocBuf;
1529 pThis->INetworkUp.pfnFreeBuf = drvNATNetworkUp_FreeBuf;
1530 pThis->INetworkUp.pfnSendBuf = drvNATNetworkUp_SendBuf;
1531 pThis->INetworkUp.pfnEndXmit = drvNATNetworkUp_EndXmit;
1532 pThis->INetworkUp.pfnSetPromiscuousMode = drvNATNetworkUp_SetPromiscuousMode;
1533 pThis->INetworkUp.pfnNotifyLinkChanged = drvNATNetworkUp_NotifyLinkChanged;
1534
1535 /* NAT engine configuration */
1536 pThis->INetworkNATCfg.pfnRedirectRuleCommand = drvNATNetworkNatConfigRedirect;
1537 pThis->INetworkNATCfg.pfnNotifyDnsChanged = drvNATNotifyDnsChanged;
1538
1539 /*
1540 * Validate the config.
1541 */
1542 PDMDRV_VALIDATE_CONFIG_RETURN(pDrvIns,
1543 "PassDomain"
1544 "|TFTPPrefix"
1545 "|BootFile"
1546 "|Network"
1547 "|NextServer"
1548 "|DNSProxy"
1549 "|BindIP"
1550 "|UseHostResolver"
1551 "|SlirpMTU"
1552 "|AliasMode"
1553 "|SockRcv"
1554 "|SockSnd"
1555 "|TcpRcv"
1556 "|TcpSnd"
1557 "|ICMPCacheLimit"
1558 "|SoMaxConnection"
1559 "|LocalhostReachable"
1560 "|HostResolverMappings"
1561 , "PortForwarding");
1562
1563 /*
1564 * Get the configuration settings.
1565 */
1566 int rc;
1567 bool fPassDomain = true;
1568 GET_BOOL(rc, pDrvIns, pCfg, "PassDomain", fPassDomain);
1569
1570 GET_STRING_ALLOC(rc, pDrvIns, pCfg, "TFTPPrefix", pThis->pszTFTPPrefix);
1571 GET_STRING_ALLOC(rc, pDrvIns, pCfg, "BootFile", pThis->pszBootFile);
1572 GET_STRING_ALLOC(rc, pDrvIns, pCfg, "NextServer", pThis->pszNextServer);
1573
1574 int fDNSProxy = 0;
1575 GET_S32(rc, pDrvIns, pCfg, "DNSProxy", fDNSProxy);
1576 int MTU = 1500;
1577 GET_S32(rc, pDrvIns, pCfg, "SlirpMTU", MTU);
1578 int i32AliasMode = 0;
1579 int i32MainAliasMode = 0;
1580 GET_S32(rc, pDrvIns, pCfg, "AliasMode", i32MainAliasMode);
1581 int iIcmpCacheLimit = 100;
1582 GET_S32(rc, pDrvIns, pCfg, "ICMPCacheLimit", iIcmpCacheLimit);
1583 bool fLocalhostReachable = false;
1584 GET_BOOL(rc, pDrvIns, pCfg, "LocalhostReachable", fLocalhostReachable);
1585
1586 i32AliasMode |= (i32MainAliasMode & 0x1 ? 0x1 : 0);
1587 i32AliasMode |= (i32MainAliasMode & 0x2 ? 0x40 : 0);
1588 i32AliasMode |= (i32MainAliasMode & 0x4 ? 0x4 : 0);
1589 int i32SoMaxConn = 10;
1590 GET_S32(rc, pDrvIns, pCfg, "SoMaxConnection", i32SoMaxConn);
1591 /*
1592 * Query the network port interface.
1593 */
1594 pThis->pIAboveNet = PDMIBASE_QUERY_INTERFACE(pDrvIns->pUpBase, PDMINETWORKDOWN);
1595 if (!pThis->pIAboveNet)
1596 return PDMDRV_SET_ERROR(pDrvIns, VERR_PDM_MISSING_INTERFACE_ABOVE,
1597 N_("Configuration error: the above device/driver didn't "
1598 "export the network port interface"));
1599 pThis->pIAboveConfig = PDMIBASE_QUERY_INTERFACE(pDrvIns->pUpBase, PDMINETWORKCONFIG);
1600 if (!pThis->pIAboveConfig)
1601 return PDMDRV_SET_ERROR(pDrvIns, VERR_PDM_MISSING_INTERFACE_ABOVE,
1602 N_("Configuration error: the above device/driver didn't "
1603 "export the network config interface"));
1604
1605 /* Generate a network address for this network card. */
1606 char szNetwork[32]; /* xxx.xxx.xxx.xxx/yy */
1607 GET_STRING(rc, pDrvIns, pCfg, "Network", szNetwork[0], sizeof(szNetwork));
1608 if (rc == VERR_CFGM_VALUE_NOT_FOUND)
1609 return PDMDrvHlpVMSetError(pDrvIns, rc, RT_SRC_POS, N_("NAT%d: Configuration error: missing network"),
1610 pDrvIns->iInstance);
1611
1612 RTNETADDRIPV4 Network, Netmask, Nettemp;
1613 rc = RTCidrStrToIPv4(szNetwork, &Network, &Netmask);
1614 if (RT_FAILURE(rc))
1615 return PDMDrvHlpVMSetError(pDrvIns, rc, RT_SRC_POS,
1616 N_("NAT#%d: Configuration error: network '%s' describes not a valid IPv4 network"),
1617 pDrvIns->iInstance, szNetwork);
1618
1619 /* Construct Libslirp Config and Initialzie Slirp */
1620
1621 LogFlow(("Here is what is coming out of the vbox config (NAT#%d):\n"
1622 " Network: %RTnaipv4\n"
1623 " Netmask: %RTnaipv4\n",
1624 pDrvIns->iInstance, RT_H2BE_U32(Network.u), RT_H2BE_U32(Netmask.u)));
1625
1626 struct in_addr vnetwork = RTNetIPv4AddrHEToInAddr(&Network);
1627 struct in_addr vnetmask = RTNetIPv4AddrHEToInAddr(&Netmask);
1628 Nettemp = Network; Nettemp.u |= 2; /* Usually 10.0.2.2 */
1629 struct in_addr vhost = RTNetIPv4AddrHEToInAddr(&Nettemp);
1630 Nettemp = Network; Nettemp.u |= 15; /* Usually 10.0.2.15 */
1631 struct in_addr vdhcp_start = RTNetIPv4AddrHEToInAddr(&Nettemp);
1632 Nettemp = Network; Nettemp.u |= 3; /* Usually 10.0.2.3 */
1633 struct in_addr vnameserver = RTNetIPv4AddrHEToInAddr(&Nettemp);
1634
1635 SlirpConfig slirpCfg = { 0 };
1636 static SlirpCb slirpCallbacks = { 0 };
1637
1638 slirpCfg.version = 4;
1639 slirpCfg.restricted = false;
1640 slirpCfg.in_enabled = true;
1641 slirpCfg.vnetwork = vnetwork;
1642 slirpCfg.vnetmask = vnetmask;
1643 slirpCfg.vhost = vhost;
1644 slirpCfg.in6_enabled = true;
1645
1646 /*
1647 * Use the same prefix as the NAT Network default:
1648 * [fd17:625c:f037:XXXX::/64] - RFC 4193 (ULA) Locally Assigned
1649 * Global ID where XXXX, 16 bit Subnet ID, are two bytes from the
1650 * middle of the IPv4 address, e.g. :0002: for 10.0.2.1.
1651 */
1652
1653 inet_pton(AF_INET6, "fd17:625c:f037:0::", &slirpCfg.vprefix_addr6);
1654 inet_pton(AF_INET6, "fd17:625c:f037:0::2", &slirpCfg.vhost6);
1655 inet_pton(AF_INET6, "fd17:625c:f037:0::3", &slirpCfg.vnameserver6);
1656 slirpCfg.vprefix_len = 64;
1657
1658 /* Copy the middle of the IPv4 addresses to the IPv6 addresses. */
1659 slirpCfg.vprefix_addr6.s6_addr[6] = RT_BYTE2(vhost.s_addr);
1660 slirpCfg.vprefix_addr6.s6_addr[7] = RT_BYTE3(vhost.s_addr);
1661 slirpCfg.vhost6.s6_addr[6] = RT_BYTE2(vhost.s_addr);
1662 slirpCfg.vhost6.s6_addr[7] = RT_BYTE3(vhost.s_addr);
1663 slirpCfg.vnameserver6.s6_addr[6] = RT_BYTE2(vnameserver.s_addr);
1664 slirpCfg.vnameserver6.s6_addr[7] = RT_BYTE3(vnameserver.s_addr);
1665
1666 slirpCfg.vhostname = "vbox";
1667 slirpCfg.tftp_server_name = pThis->pszNextServer;
1668 slirpCfg.tftp_path = pThis->pszTFTPPrefix;
1669 slirpCfg.bootfile = pThis->pszBootFile;
1670 slirpCfg.vdhcp_start = vdhcp_start;
1671 slirpCfg.vnameserver = vnameserver;
1672 slirpCfg.if_mtu = MTU;
1673
1674 slirpCfg.vdnssearch = NULL;
1675 slirpCfg.vdomainname = NULL;
1676
1677 slirpCallbacks.send_packet = &drvNAT_SendPacketCb;
1678 slirpCallbacks.guest_error = &drvNAT_GuestErrorCb;
1679 slirpCallbacks.clock_get_ns = &drvNAT_ClockGetNsCb;
1680 slirpCallbacks.timer_new = &drvNAT_TimerNewCb;
1681 slirpCallbacks.timer_free = &drvNAT_TimerFreeCb;
1682 slirpCallbacks.timer_mod = &drvNAT_TimerModCb;
1683 slirpCallbacks.register_poll_fd = &drvNAT_RegisterPoll;
1684 slirpCallbacks.unregister_poll_fd = &drvNAT_UnregisterPoll;
1685 slirpCallbacks.notify = &drvNAT_NotifyCb;
1686 slirpCallbacks.init_completed = NULL;
1687 slirpCallbacks.timer_new_opaque = NULL;
1688
1689 Slirp *pSlirp = slirp_new(/* cfg */ &slirpCfg, /* callbacks */ &slirpCallbacks, /* opaque */ pThis);
1690
1691 if (pSlirp == NULL)
1692 return VERR_INVALID_POINTER;
1693
1694 pThis->pNATState->pSlirp = pSlirp;
1695
1696 rc = drvNATConstructRedir(pDrvIns->iInstance, pThis, pCfg, &Network);
1697 AssertLogRelRCReturn(rc, rc);
1698
1699 rc = PDMDrvHlpSSMRegisterLoadDone(pDrvIns, NULL);
1700 AssertLogRelRCReturn(rc, rc);
1701
1702 rc = RTReqQueueCreate(&pThis->hSlirpReqQueue);
1703 AssertLogRelRCReturn(rc, rc);
1704
1705 rc = RTReqQueueCreate(&pThis->hRecvReqQueue);
1706 AssertLogRelRCReturn(rc, rc);
1707
1708 rc = PDMDrvHlpThreadCreate(pDrvIns, &pThis->pRecvThread, pThis, drvNATRecv,
1709 drvNATRecvWakeup, 256 * _1K, RTTHREADTYPE_IO, "NATRX");
1710 AssertRCReturn(rc, rc);
1711
1712 rc = RTSemEventCreate(&pThis->EventRecv);
1713 AssertRCReturn(rc, rc);
1714
1715 rc = RTCritSectInit(&pThis->DevAccessLock);
1716 AssertRCReturn(rc, rc);
1717
1718 rc = RTCritSectInit(&pThis->XmitLock);
1719 AssertRCReturn(rc, rc);
1720
1721 char szTmp[128];
1722 RTStrPrintf(szTmp, sizeof(szTmp), "nat%d", pDrvIns->iInstance);
1723 PDMDrvHlpDBGFInfoRegister(pDrvIns, szTmp, "NAT info.", drvNATInfo);
1724
1725#ifdef VBOX_WITH_STATISTICS
1726# define DRV_PROFILE_COUNTER(name, dsc) REGISTER_COUNTER(name, pThis, STAMTYPE_PROFILE, STAMUNIT_TICKS_PER_CALL, dsc)
1727# define DRV_COUNTING_COUNTER(name, dsc) REGISTER_COUNTER(name, pThis, STAMTYPE_COUNTER, STAMUNIT_COUNT, dsc)
1728# include "slirp/counters.h"
1729#endif
1730
1731#ifndef RT_OS_WINDOWS
1732 // Create the control pipe.
1733 rc = RTPipeCreate(&pThis->hPipeRead, &pThis->hPipeWrite, 0 /*fFlags*/);
1734 AssertRCReturn(rc, rc);
1735#else
1736 // Create the wakeup socket pair.
1737 pThis->pWakeupSockPair[0] = NULL;
1738 pThis->pWakeupSockPair[1] = NULL;
1739
1740 /* idx=0 is write, idx=1 is read */
1741 rc = RTWinSocketPair(AF_INET, SOCK_DGRAM, 0, pThis->pWakeupSockPair);
1742 AssertRCReturn(rc, rc);
1743#endif
1744 /* initalize the notifier counter */
1745 pThis->cbWakeupNotifs = 0;
1746
1747 rc = PDMDrvHlpThreadCreate(pDrvIns, &pThis->pSlirpThread, pThis, drvNATAsyncIoThread,
1748 drvNATAsyncIoWakeup, 256 * _1K, RTTHREADTYPE_IO, "NAT");
1749 AssertRCReturn(rc, rc);
1750
1751 pThis->enmLinkState = pThis->enmLinkStateWant = PDMNETWORKLINKSTATE_UP;
1752
1753 return rc;
1754}
1755
1756/**
1757 * NAT network transport driver registration record.
1758 */
1759const PDMDRVREG g_DrvNATlibslirp =
1760{
1761 /* u32Version */
1762 PDM_DRVREG_VERSION,
1763 /* szName */
1764 "NAT",
1765 /* szRCMod */
1766 "",
1767 /* szR0Mod */
1768 "",
1769 /* pszDescription */
1770 "NATlibslrip Network Transport Driver",
1771 /* fFlags */
1772 PDM_DRVREG_FLAGS_HOST_BITS_DEFAULT,
1773 /* fClass. */
1774 PDM_DRVREG_CLASS_NETWORK,
1775 /* cMaxInstances */
1776 ~0U,
1777 /* cbInstance */
1778 sizeof(DRVNAT),
1779 /* pfnConstruct */
1780 drvNATConstruct,
1781 /* pfnDestruct */
1782 drvNATDestruct,
1783 /* pfnRelocate */
1784 NULL,
1785 /* pfnIOCtl */
1786 NULL,
1787 /* pfnPowerOn */
1788 NULL,
1789 /* pfnReset */
1790 NULL,
1791 /* pfnSuspend */
1792 NULL,
1793 /* pfnResume */
1794 NULL,
1795 /* pfnAttach */
1796 NULL,
1797 /* pfnDetach */
1798 NULL,
1799 /* pfnPowerOff */
1800 NULL,
1801 /* pfnSoftReset */
1802 NULL,
1803 /* u32EndVersion */
1804 PDM_DRVREG_VERSION
1805};
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