VirtualBox

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

Last change on this file was 106061, checked in by vboxsync, 3 weeks ago

Copyright year updates by scm.

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