VirtualBox

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

Last change on this file since 105084 was 105084, checked in by vboxsync, 10 months ago

Devices/Network: fix build issue. bugref:10268

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

© 2025 Oracle Support Privacy / Do Not Sell My Info Terms of Use Trademark Policy Automated Access Etiquette