VirtualBox

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

Last change on this file since 106250 was 106250, checked in by vboxsync, 7 weeks ago

Devices/Network: added some release logging. bugref:10268

  • Property svn:eol-style set to native
  • Property svn:keywords set to Author Date Id Revision
File size: 58.7 KB
Line 
1/* $Id: DrvNATlibslirp.cpp 106250 2024-10-08 22:43:46Z 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_DOWN\n"));
469 return VERR_NET_DOWN;
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 LogRel(("NAT: WSAPoll returned %d (error %d)\n", cChangedFDs, error));
794 Log4(("NAT: 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 LogRel(("NAT: DNS settings changed, triggering update\n"));
1056
1057 if (pDnsConf->szDomainName[0] == '\0')
1058 slirp_set_vdomainname(pNATState->pSlirp, NULL);
1059 else
1060 slirp_set_vdomainname(pNATState->pSlirp, pDnsConf->szDomainName);
1061
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 // Create the control pipe.
1702 rc = RTPipeCreate(&pThis->hPipeRead, &pThis->hPipeWrite, 0 /*fFlags*/);
1703 AssertRCReturn(rc, rc);
1704#else
1705 // Create the wakeup event handle.
1706 pThis->hWakeupEvent = NULL;
1707 pThis->hWakeupEvent = CreateEvent(NULL, FALSE, FALSE, NULL); /* auto-reset event */
1708 Assert(pThis->hWakeupEvent != NULL);
1709#endif
1710
1711 rc = PDMDrvHlpThreadCreate(pDrvIns, &pThis->pSlirpThread, pThis, drvNATAsyncIoThread,
1712 drvNATAsyncIoWakeup, 256 * _1K, RTTHREADTYPE_IO, "NAT");
1713 AssertRCReturn(rc, rc);
1714
1715 pThis->enmLinkState = pThis->enmLinkStateWant = PDMNETWORKLINKSTATE_UP;
1716
1717 return rc;
1718}
1719
1720/**
1721 * NAT network transport driver registration record.
1722 */
1723const PDMDRVREG g_DrvNATlibslirp =
1724{
1725 /* u32Version */
1726 PDM_DRVREG_VERSION,
1727 /* szName */
1728 "NAT",
1729 /* szRCMod */
1730 "",
1731 /* szR0Mod */
1732 "",
1733 /* pszDescription */
1734 "NATlibslrip Network Transport Driver",
1735 /* fFlags */
1736 PDM_DRVREG_FLAGS_HOST_BITS_DEFAULT,
1737 /* fClass. */
1738 PDM_DRVREG_CLASS_NETWORK,
1739 /* cMaxInstances */
1740 ~0U,
1741 /* cbInstance */
1742 sizeof(DRVNAT),
1743 /* pfnConstruct */
1744 drvNATConstruct,
1745 /* pfnDestruct */
1746 drvNATDestruct,
1747 /* pfnRelocate */
1748 NULL,
1749 /* pfnIOCtl */
1750 NULL,
1751 /* pfnPowerOn */
1752 NULL,
1753 /* pfnReset */
1754 NULL,
1755 /* pfnSuspend */
1756 NULL,
1757 /* pfnResume */
1758 NULL,
1759 /* pfnAttach */
1760 NULL,
1761 /* pfnDetach */
1762 NULL,
1763 /* pfnPowerOff */
1764 NULL,
1765 /* pfnSoftReset */
1766 NULL,
1767 /* u32EndVersion */
1768 PDM_DRVREG_VERSION
1769};
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