VirtualBox

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

Last change on this file since 107328 was 107225, checked in by vboxsync, 2 months ago

NAT: Slightly adjusted polling loop.

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