VirtualBox

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

Last change on this file since 106608 was 106608, checked in by vboxsync, 5 weeks ago

Devices/Network: switched back to poll paradigm for windows and non-windows. bugref:10268

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