VirtualBox

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

Last change on this file since 106129 was 106129, checked in by vboxsync, 5 months ago

Devices/Network: Fix windows slow packet throughput by kicking NAT thread more regularly. bugref:10268

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