VirtualBox

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

Last change on this file since 105202 was 105202, checked in by vboxsync, 9 months ago

Devices/Network: clean and reorganized code, fix win warnings. bugref:10268

  • Property svn:eol-style set to native
  • Property svn:keywords set to Author Date Id Revision
File size: 48.5 KB
Line 
1/* $Id: DrvNATlibslirp.cpp 105202 2024-07-08 22:42:06Z 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 * PDM Function Implementations
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 = 0;
371#ifndef RT_OS_WINDOWS
372 /* kick poll() */
373 size_t cbIgnored;
374 rc = RTPipeWrite(pThis->hPipeWrite, "", 1, &cbIgnored);
375#else
376 RT_NOREF(pThis);
377#endif
378 AssertRC(rc);
379}
380
381/**
382 * @interface_method_impl{PDMINETWORKUP,pfnSetPromiscuousMode}
383 */
384static DECLCALLBACK(void) drvNATNetworkUp_SetPromiscuousMode(PPDMINETWORKUP pInterface, bool fPromiscuous)
385{
386 RT_NOREF(pInterface, fPromiscuous);
387 LogFlow(("drvNATNetworkUp_SetPromiscuousMode: fPromiscuous=%d\n", fPromiscuous));
388 /* nothing to do */
389}
390
391/**
392 * Worker function for drvNATNetworkUp_NotifyLinkChanged().
393 * @thread "NAT" thread.
394 *
395 * @param pThis Pointer to DRVNAT state for current context.
396 * @param enmLinkState Enum value of link state.
397 *
398 * @thread NAT
399 */
400static DECLCALLBACK(void) drvNATNotifyLinkChangedWorker(PDRVNAT pThis, PDMNETWORKLINKSTATE enmLinkState)
401{
402 pThis->enmLinkState = pThis->enmLinkStateWant = enmLinkState;
403 switch (enmLinkState)
404 {
405 case PDMNETWORKLINKSTATE_UP:
406 LogRel(("NAT: Link up\n"));
407 break;
408
409 case PDMNETWORKLINKSTATE_DOWN:
410 case PDMNETWORKLINKSTATE_DOWN_RESUME:
411 LogRel(("NAT: Link down\n"));
412 break;
413
414 default:
415 AssertMsgFailed(("drvNATNetworkUp_NotifyLinkChanged: unexpected link state %d\n", enmLinkState));
416 }
417}
418
419/**
420 * Notification on link status changes.
421 *
422 * @param pInterface Pointer to the interface structure containing the called function pointer.
423 * @param enmLinkState The new link state.
424 *
425 * @thread EMT
426 */
427static DECLCALLBACK(void) drvNATNetworkUp_NotifyLinkChanged(PPDMINETWORKUP pInterface, PDMNETWORKLINKSTATE enmLinkState)
428{
429 PDRVNAT pThis = RT_FROM_MEMBER(pInterface, DRVNAT, INetworkUp);
430
431 LogFlow(("drvNATNetworkUp_NotifyLinkChanged: enmLinkState=%d\n", enmLinkState));
432
433 /* Don't queue new requests if the NAT thread is not running (e.g. paused,
434 * stopping), otherwise we would deadlock. Memorize the change. */
435 if (pThis->pSlirpThread->enmState != PDMTHREADSTATE_RUNNING)
436 {
437 pThis->enmLinkStateWant = enmLinkState;
438 return;
439 }
440
441 PRTREQ pReq;
442 int rc = RTReqQueueCallEx(pThis->hSlirpReqQueue, &pReq, 0 /*cMillies*/, RTREQFLAGS_VOID,
443 (PFNRT)drvNATNotifyLinkChangedWorker, 2, pThis, enmLinkState);
444 if (rc == VERR_TIMEOUT)
445 {
446 drvNATNotifyNATThread(pThis, "drvNATNetworkUp_NotifyLinkChanged");
447 rc = RTReqWait(pReq, RT_INDEFINITE_WAIT);
448 AssertRC(rc);
449 }
450 else
451 AssertRC(rc);
452 RTReqRelease(pReq);
453}
454
455/**
456 * NAT thread handling the slirp stuff.
457 *
458 * The slirp implementation is single-threaded so we execute this enginre in a
459 * dedicated thread. We take care that this thread does not become the
460 * bottleneck: If the guest wants to send, a request is enqueued into the
461 * hSlirpReqQueue and handled asynchronously by this thread. If this thread
462 * wants to deliver packets to the guest, it enqueues a request into
463 * hRecvReqQueue which is later handled by the Recv thread.
464 *
465 * @param pDrvIns Pointer to PDM driver context.
466 * @param pThread Pointer to calling thread context.
467 *
468 * @returns VBox status code
469 *
470 * @thread NAT
471 */
472static DECLCALLBACK(int) drvNATAsyncIoThread(PPDMDRVINS pDrvIns, PPDMTHREAD pThread)
473{
474 PDRVNAT pThis = PDMINS_2_DATA(pDrvIns, PDRVNAT);
475#ifdef RT_OS_WINDOWS
476 unsigned int cBreak = 0;
477#else /* RT_OS_WINDOWS */
478 unsigned int cPollNegRet = 0;
479 drvNAT_AddPollCb(RTPipeToNative(pThis->hPipeRead), SLIRP_POLL_IN | SLIRP_POLL_HUP, pThis);
480 pThis->pNATState->polls[0].fd = RTPipeToNative(pThis->hPipeRead);
481 pThis->pNATState->polls[0].events = POLLRDNORM | POLLPRI | POLLRDBAND;
482 pThis->pNATState->polls[0].revents = 0;
483#endif /* !RT_OS_WINDOWS */
484
485 LogFlow(("drvNATAsyncIoThread: pThis=%p\n", pThis));
486
487 if (pThread->enmState == PDMTHREADSTATE_INITIALIZING)
488 return VINF_SUCCESS;
489
490 if (pThis->enmLinkStateWant != pThis->enmLinkState)
491 drvNATNotifyLinkChangedWorker(pThis, pThis->enmLinkStateWant);
492
493 /*
494 * Polling loop.
495 */
496 while (pThread->enmState == PDMTHREADSTATE_RUNNING)
497 {
498 /*
499 * To prevent concurrent execution of sending/receiving threads
500 */
501#ifndef RT_OS_WINDOWS
502 uint32_t uTimeout = 0;
503 pThis->pNATState->nsock = 1;
504
505 slirp_pollfds_fill(pThis->pNATState->pSlirp, &uTimeout, drvNAT_AddPollCb /* SlirpAddPollCb */, pThis /* opaque */);
506 drvNAT_UpdateTimeout(&uTimeout, pThis);
507
508 int cChangedFDs = poll(pThis->pNATState->polls, pThis->pNATState->nsock, uTimeout /* timeout */);
509
510 if (cChangedFDs < 0)
511 {
512 if (errno == EINTR)
513 {
514 Log2(("NAT: signal was caught while sleep on poll\n"));
515 /* No error, just process all outstanding requests but don't wait */
516 cChangedFDs = 0;
517 }
518 else if (cPollNegRet++ > 128)
519 {
520 LogRel(("NAT: Poll returns (%s) suppressed %d\n", strerror(errno), cPollNegRet));
521 cPollNegRet = 0;
522 }
523 }
524
525
526 slirp_pollfds_poll(pThis->pNATState->pSlirp, cChangedFDs < 0, drvNAT_GetREventsCb /* SlirpGetREventsCb */, pThis /* opaque */);
527 if (pThis->pNATState->polls[0].revents & (POLLRDNORM|POLLPRI|POLLRDBAND))
528 {
529 /* drain the pipe
530 *
531 * Note! drvNATSend decoupled so we don't know how many times
532 * device's thread sends before we've entered multiplex,
533 * so to avoid false alarm drain pipe here to the very end
534 *
535 * @todo: Probably we should counter drvNATSend to count how
536 * deep pipe has been filed before drain.
537 *
538 */
539 /** @todo XXX: Make it reading exactly we need to drain the
540 * pipe.*/
541 char ch;
542 size_t cbRead;
543 RTPipeRead(pThis->hPipeRead, &ch, 1, &cbRead);
544 }
545
546 /* process _all_ outstanding requests but don't wait */
547 RTReqQueueProcess(pThis->hSlirpReqQueue, 0);
548 drvNAT_CheckTimeout(pThis);
549
550#else /* RT_OS_WINDOWS */
551 uint32_t uTimeout = 0;
552 pThis->pNATState->nsock = 0;
553 slirp_pollfds_fill(pThis->pNATState->pSlirp, &uTimeout, drvNAT_AddPollCb /* SlirpAddPollCb */, pThis /* opaque */);
554 drvNAT_UpdateTimeout(&uTimeout, pThis);
555
556 int cChangedFDs = WSAPoll(pThis->pNATState->polls, pThis->pNATState->nsock, uTimeout /* timeout */);
557 int error = WSAGetLastError();
558
559 if (cChangedFDs < 0)
560 {
561 LogFlow(("NAT: WSAPoll returned %d (error %d)\n", cChangedFDs, error));
562 LogFlow(("NSOCK = %d\n", pThis->pNATState->nsock));
563
564 if (error == 10022)
565 RTThreadSleep(100);
566 }
567
568 if (cChangedFDs == 0)
569 {
570 /* only check for slow/fast timers */
571 slirp_pollfds_poll(pThis->pNATState->pSlirp, false /*select error*/, drvNAT_GetREventsCb /* SlirpGetREventsCb */, pThis /* opaque */);
572 RTReqQueueProcess(pThis->hSlirpReqQueue, 0);
573 continue;
574 }
575 /* poll the sockets in any case */
576 Log2(("%s: poll\n", __FUNCTION__));
577 slirp_pollfds_poll(pThis->pNATState->pSlirp, cChangedFDs < 0 /*select error*/, drvNAT_GetREventsCb /* SlirpGetREventsCb */, pThis /* opaque */);
578
579 /* process _all_ outstanding requests but don't wait */
580 RTReqQueueProcess(pThis->hSlirpReqQueue, 0);
581 drvNAT_CheckTimeout(pThis);
582# ifdef VBOX_NAT_DELAY_HACK
583 if (cBreak++ > 128)
584 {
585 cBreak = 0;
586 RTThreadSleep(2);
587 }
588# endif
589#endif /* RT_OS_WINDOWS */
590 }
591
592 return VINF_SUCCESS;
593}
594
595/**
596 * Unblock the send thread so it can respond to a state change.
597 *
598 * @returns VBox status code.
599 * @param pDrvIns The pcnet device instance.
600 * @param pThread The send thread.
601 *
602 * @thread ?
603 */
604static DECLCALLBACK(int) drvNATAsyncIoWakeup(PPDMDRVINS pDrvIns, PPDMTHREAD pThread)
605{
606 RT_NOREF(pThread);
607 PDRVNAT pThis = PDMINS_2_DATA(pDrvIns, PDRVNAT);
608
609 drvNATNotifyNATThread(pThis, "drvNATAsyncIoWakeup");
610 return VINF_SUCCESS;
611}
612
613/**
614 * @interface_method_impl{PDMIBASE,pfnQueryInterface}
615 */
616static DECLCALLBACK(void *) drvNATQueryInterface(PPDMIBASE pInterface, const char *pszIID)
617{
618 PPDMDRVINS pDrvIns = PDMIBASE_2_PDMDRV(pInterface);
619 PDRVNAT pThis = PDMINS_2_DATA(pDrvIns, PDRVNAT);
620
621 PDMIBASE_RETURN_INTERFACE(pszIID, PDMIBASE, &pDrvIns->IBase);
622 PDMIBASE_RETURN_INTERFACE(pszIID, PDMINETWORKUP, &pThis->INetworkUp);
623 PDMIBASE_RETURN_INTERFACE(pszIID, PDMINETWORKNATCONFIG, &pThis->INetworkNATCfg);
624 return NULL;
625}
626
627/**
628 * Info handler.
629 *
630 * @param pDrvIns The PDM driver context.
631 * @param pHlp ....
632 * @param pszArgs Unused.
633 *
634 * @thread any
635 */
636static DECLCALLBACK(void) drvNATInfo(PPDMDRVINS pDrvIns, PCDBGFINFOHLP pHlp, const char *pszArgs)
637{
638 RT_NOREF(pszArgs);
639 PDRVNAT pThis = PDMINS_2_DATA(pDrvIns, PDRVNAT);
640 pHlp->pfnPrintf(pHlp, "libslirp Connection Info:\n");
641 pHlp->pfnPrintf(pHlp, slirp_connection_info(pThis->pNATState->pSlirp));
642 pHlp->pfnPrintf(pHlp, "libslirp Neighbor Info:\n");
643 pHlp->pfnPrintf(pHlp, slirp_neighbor_info(pThis->pNATState->pSlirp));
644 pHlp->pfnPrintf(pHlp, "libslirp Version String: %s \n", slirp_version_string());
645}
646
647/**
648 * Sets up the redirectors.
649 *
650 * @returns VBox status code.
651 * @param uInstance ?
652 * @param pThis ?
653 * @param pCfg The configuration handle.
654 * @param pNetwork Unused.
655 *
656 * @thread ?
657 */
658static int drvNATConstructRedir(unsigned iInstance, PDRVNAT pThis, PCFGMNODE pCfg, PRTNETADDRIPV4 pNetwork)
659{
660 /** @todo r=jack: rewrite to support IPv6? */
661 PPDMDRVINS pDrvIns = pThis->pDrvIns;
662 PCPDMDRVHLPR3 pHlp = pDrvIns->pHlpR3;
663
664 RT_NOREF(pNetwork); /** @todo figure why pNetwork isn't used */
665
666 PCFGMNODE pPFTree = pHlp->pfnCFGMGetChild(pCfg, "PortForwarding");
667 if (pPFTree == NULL)
668 return VINF_SUCCESS;
669
670 /*
671 * Enumerate redirections.
672 */
673 for (PCFGMNODE pNode = pHlp->pfnCFGMGetFirstChild(pPFTree); pNode; pNode = pHlp->pfnCFGMGetNextChild(pNode))
674 {
675 /*
676 * Validate the port forwarding config.
677 */
678 if (!pHlp->pfnCFGMAreValuesValid(pNode, "Name\0Protocol\0UDP\0HostPort\0GuestPort\0GuestIP\0BindIP\0"))
679 return PDMDRV_SET_ERROR(pDrvIns, VERR_PDM_DRVINS_UNKNOWN_CFG_VALUES,
680 N_("Unknown configuration in port forwarding"));
681
682 /* protocol type */
683 bool fUDP;
684 char szProtocol[32];
685 int rc;
686 GET_STRING(rc, pDrvIns, pNode, "Protocol", szProtocol[0], sizeof(szProtocol));
687 if (rc == VERR_CFGM_VALUE_NOT_FOUND)
688 {
689 fUDP = false;
690 GET_BOOL(rc, pDrvIns, pNode, "UDP", fUDP);
691 }
692 else if (RT_SUCCESS(rc))
693 {
694 if (!RTStrICmp(szProtocol, "TCP"))
695 fUDP = false;
696 else if (!RTStrICmp(szProtocol, "UDP"))
697 fUDP = true;
698 else
699 return PDMDrvHlpVMSetError(pDrvIns, VERR_INVALID_PARAMETER, RT_SRC_POS,
700 N_("NAT#%d: Invalid configuration value for \"Protocol\": \"%s\""),
701 iInstance, szProtocol);
702 }
703 else
704 return PDMDrvHlpVMSetError(pDrvIns, rc, RT_SRC_POS,
705 N_("NAT#%d: configuration query for \"Protocol\" failed"),
706 iInstance);
707 /* host port */
708 int32_t iHostPort;
709 GET_S32_STRICT(rc, pDrvIns, pNode, "HostPort", iHostPort);
710
711 /* guest port */
712 int32_t iGuestPort;
713 GET_S32_STRICT(rc, pDrvIns, pNode, "GuestPort", iGuestPort);
714
715 /* host address ("BindIP" name is rather unfortunate given "HostPort" to go with it) */
716 struct in_addr BindIP;
717 RT_ZERO(BindIP);
718 GETIP_DEF(rc, pDrvIns, pNode, BindIP, INADDR_ANY);
719
720 /* guest address */
721 struct in_addr GuestIP;
722 RT_ZERO(GuestIP);
723 GETIP_DEF(rc, pDrvIns, pNode, GuestIP, INADDR_ANY);
724
725 /*
726 * Call slirp about it.
727 */
728 if (slirp_add_hostfwd(pThis->pNATState->pSlirp, fUDP, BindIP,
729 iHostPort, GuestIP, iGuestPort) < 0)
730 return PDMDrvHlpVMSetError(pThis->pDrvIns, VERR_NAT_REDIR_SETUP, RT_SRC_POS,
731 N_("NAT#%d: configuration error: failed to set up "
732 "redirection of %d to %d. Probably a conflict with "
733 "existing services or other rules"), iInstance, iHostPort,
734 iGuestPort);
735 } /* for each redir rule */
736
737 return VINF_SUCCESS;
738}
739
740/**
741 * Applies port forwarding between guest and host.
742 *
743 * @param pThis Pointer to DRVNAT state for current context.
744 * @param fRemove Flag to remove port forward instead of create.
745 * @param fUdp Flag specifying if UDP. If false, TCP.
746 * @param pHostIp String of host IP address.
747 * @param u16HostPort Host port to forward to.
748 * @param pGuestIp String of guest IP address.
749 * @param u16GuestPort Guest port to forward.
750 *
751 * @thread ?
752 */
753static DECLCALLBACK(void) drvNATNotifyApplyPortForwardCommand(PDRVNAT pThis, bool fRemove,
754 bool fUdp, const char *pHostIp,
755 uint16_t u16HostPort, const char *pGuestIp, uint16_t u16GuestPort)
756{
757 /** @todo r=jack:
758 * - rewrite for IPv6
759 * - do we want to lock the guestIp to the VMs IP?
760 */
761 struct in_addr guestIp, hostIp;
762
763 if ( pHostIp == NULL
764 || inet_aton(pHostIp, &hostIp) == 0)
765 hostIp.s_addr = INADDR_ANY;
766
767 if ( pGuestIp == NULL
768 || inet_aton(pGuestIp, &guestIp) == 0)
769 guestIp.s_addr = pThis->GuestIP;
770
771 if (fRemove)
772 slirp_remove_hostfwd(pThis->pNATState->pSlirp, fUdp, hostIp, u16HostPort);
773 else
774 slirp_add_hostfwd(pThis->pNATState->pSlirp, fUdp, hostIp,
775 u16HostPort, guestIp, u16GuestPort);
776}
777
778static DECLCALLBACK(int) drvNATNetworkNatConfigRedirect(PPDMINETWORKNATCONFIG pInterface, bool fRemove,
779 bool fUdp, const char *pHostIp, uint16_t u16HostPort,
780 const char *pGuestIp, uint16_t u16GuestPort)
781{
782 LogFlowFunc(("fRemove=%d, fUdp=%d, pHostIp=%s, u16HostPort=%u, pGuestIp=%s, u16GuestPort=%u\n",
783 RT_BOOL(fRemove), RT_BOOL(fUdp), pHostIp, u16HostPort, pGuestIp, u16GuestPort));
784 PDRVNAT pThis = RT_FROM_MEMBER(pInterface, DRVNAT, INetworkNATCfg);
785 /* Execute the command directly if the VM is not running. */
786 int rc;
787 if (pThis->pSlirpThread->enmState != PDMTHREADSTATE_RUNNING)
788 {
789 drvNATNotifyApplyPortForwardCommand(pThis, fRemove, fUdp, pHostIp,
790 u16HostPort, pGuestIp,u16GuestPort);
791 rc = VINF_SUCCESS;
792 }
793 else
794 {
795 PRTREQ pReq;
796 rc = RTReqQueueCallEx(pThis->hSlirpReqQueue, &pReq, 0 /*cMillies*/, RTREQFLAGS_VOID,
797 (PFNRT)drvNATNotifyApplyPortForwardCommand, 7, pThis, fRemove,
798 fUdp, pHostIp, u16HostPort, pGuestIp, u16GuestPort);
799 if (rc == VERR_TIMEOUT)
800 {
801 drvNATNotifyNATThread(pThis, "drvNATNetworkNatConfigRedirect");
802 rc = RTReqWait(pReq, RT_INDEFINITE_WAIT);
803 AssertRC(rc);
804 }
805 else
806 AssertRC(rc);
807
808 RTReqRelease(pReq);
809 }
810 return rc;
811}
812
813/**
814 * Libslirp Utility Functions
815 */
816/**
817 * Update the timeout field in given list of Slirp timers.
818 *
819 * @param uTimeout Pointer to timeout value.
820 * @param opaque Pointer to NAT State context.
821 *
822 * @thread ?
823 */
824static void drvNAT_UpdateTimeout(uint32_t *uTimeout, void *opaque)
825{
826 PDRVNAT pThis = (PDRVNAT)opaque;
827 Assert(pThis);
828
829 int64_t currTime = drvNAT_ClockGetNsCb(pThis) / (1000 * 1000);
830 SlirpTimer *pCurrent = pThis->pNATState->pTimerHead;
831 while (pCurrent != NULL)
832 {
833 if (pCurrent->uTimeExpire != -1)
834 {
835 int64_t diff = pCurrent->uTimeExpire - currTime;
836
837 if (diff < 0)
838 diff = 0;
839
840 if (diff < *uTimeout)
841 *uTimeout = diff;
842 }
843
844 pCurrent = pCurrent->next;
845 }
846}
847
848/**
849 * Check if timeout has passed in given list of Slirp timers.
850 *
851 * @param opaque Pointer to NAT State context.
852 *
853 * @thread ?
854 */
855static void drvNAT_CheckTimeout(void *opaque)
856{
857 PDRVNAT pThis = (PDRVNAT)opaque;
858 Assert(pThis);
859
860 int64_t currTime = drvNAT_ClockGetNsCb(pThis) / (1000 * 1000);
861 SlirpTimer *pCurrent = pThis->pNATState->pTimerHead;
862 while (pCurrent != NULL)
863 {
864 if (pCurrent->uTimeExpire != -1)
865 {
866 int64_t diff = pCurrent->uTimeExpire - currTime;
867 if (diff <= 0)
868 {
869 pCurrent->uTimeExpire = -1;
870 pCurrent->pHandler(pCurrent->opaque);
871 }
872 }
873
874 pCurrent = pCurrent->next;
875 }
876}
877
878/**
879 * Converts slirp representation of poll events to host representation.
880 *
881 * @param iEvents Integer representing slirp type poll events.
882 *
883 * @returns Integer representing host type poll events.
884 *
885 * @thread ?
886 */
887static int drvNAT_PollEventSlirpToHost(int iEvents) {
888 int iRet = 0;
889#ifndef RT_OS_WINDOWS
890 if (iEvents & SLIRP_POLL_IN) iRet |= POLLIN;
891 if (iEvents & SLIRP_POLL_OUT) iRet |= POLLOUT;
892 if (iEvents & SLIRP_POLL_PRI) iRet |= POLLPRI;
893 if (iEvents & SLIRP_POLL_ERR) iRet |= POLLERR;
894 if (iEvents & SLIRP_POLL_HUP) iRet |= POLLHUP;
895#else
896 if (iEvents & SLIRP_POLL_IN) iRet |= (POLLRDNORM | POLLRDBAND);
897 if (iEvents & SLIRP_POLL_OUT) iRet |= POLLWRNORM;
898 if (iEvents & SLIRP_POLL_PRI) iRet |= (POLLIN);
899 if (iEvents & SLIRP_POLL_ERR) iRet |= 0;
900 if (iEvents & SLIRP_POLL_HUP) iRet |= 0;
901#endif
902 return iRet;
903}
904
905/**
906 * Converts host representation of poll events to slirp representation.
907 *
908 * @param iEvents Integer representing host type poll events.
909 *
910 * @returns Integer representing slirp type poll events.
911 *
912 * @thread ?
913 */
914static int drvNAT_PollEventHostToSlirp(int iEvents) {
915 int iRet = 0;
916#ifndef RT_OS_WINDOWS
917 if (iEvents & POLLIN) iRet |= SLIRP_POLL_IN;
918 if (iEvents & POLLOUT) iRet |= SLIRP_POLL_OUT;
919 if (iEvents & POLLPRI) iRet |= SLIRP_POLL_PRI;
920 if (iEvents & POLLERR) iRet |= SLIRP_POLL_ERR;
921 if (iEvents & POLLHUP) iRet |= SLIRP_POLL_HUP;
922#else
923 if (iEvents & (POLLRDNORM | POLLRDBAND)) iRet |= SLIRP_POLL_IN;
924 if (iEvents & POLLWRNORM) iRet |= SLIRP_POLL_OUT;
925 if (iEvents & (POLLPRI)) iRet |= SLIRP_POLL_PRI;
926 if (iEvents & POLLERR) iRet |= SLIRP_POLL_ERR;
927 if (iEvents & POLLHUP) iRet |= SLIRP_POLL_HUP;
928#endif
929 return iRet;
930}
931
932/**
933 * Libslirp Callbacks
934 */
935/**
936 * Callback called by libslirp to send packet into guest.
937 *
938 * @param pBuf Pointer to packet buffer.
939 * @param cb Size of packet.
940 * @param opaque Pointer to NAT State context.
941 *
942 * @returns Size of packet received or -1 on error.
943 *
944 * @thread ?
945 */
946static DECLCALLBACK(ssize_t) drvNAT_SendPacketCb(const void *pBuf, size_t cb, void *opaque /* PDRVNAT */)
947{
948 char *pNewBuf = (char *)RTMemAlloc(cb);
949 if (pNewBuf == NULL)
950 return -1;
951
952 memcpy(pNewBuf, pBuf, cb);
953
954 PDRVNAT pThis = (PDRVNAT)opaque;
955 Assert(pThis);
956
957 LogFlow(("slirp_output BEGIN %p %d\n", pNewBuf, cb));
958 Log6(("slirp_output: pNewBuf=%p cb=%#x (pThis=%p)\n"
959 "%.*Rhxd\n", pNewBuf, cb, pThis, cb, pNewBuf));
960
961 /* don't queue new requests when the NAT thread is about to stop */
962 if (pThis->pSlirpThread->enmState != PDMTHREADSTATE_RUNNING)
963 return -1;
964
965 ASMAtomicIncU32(&pThis->cPkts);
966 int rc = RTReqQueueCallEx(pThis->hRecvReqQueue, NULL /*ppReq*/, 0 /*cMillies*/, RTREQFLAGS_VOID | RTREQFLAGS_NO_WAIT,
967 (PFNRT)drvNATRecvWorker, 3, pThis, pNewBuf, cb);
968 AssertRC(rc);
969 drvNATRecvWakeup(pThis->pDrvIns, pThis->pRecvThread);
970 drvNATNotifyNATThread(pThis, "drvNAT_SendPacketCb");
971 STAM_COUNTER_INC(&pThis->StatQueuePktSent);
972 LogFlowFuncLeave();
973 return cb;
974}
975
976/**
977 * Callback called by libslirp on an error from a guest.
978 *
979 * @param pMsg Error message string.
980 * @param opaque Pointer to NAT State context.
981 *
982 * @thread ?
983 */
984static DECLCALLBACK(void) drvNAT_GuestErrorCb(const char *pMsg, void *opaque)
985{
986 PDRVNAT pThis = (PDRVNAT)opaque;
987 Assert(pThis);
988
989 PDMDRV_SET_ERROR(pThis->pDrvIns, VERR_PDM_UNKNOWN_DRVREG_VERSION,
990 N_("Unknown error: "));
991 LogRel((pMsg));
992}
993
994/**
995 * Callback called by libslirp to get the current timestamp in nanoseconds.
996 *
997 * @param opaque Pointer to NAT State context.
998 *
999 * @returns 64-bit signed integer representing time in nanoseconds.
1000 */
1001static DECLCALLBACK(int64_t) drvNAT_ClockGetNsCb(void *opaque)
1002{
1003 PDRVNAT pThis = (PDRVNAT)opaque;
1004 Assert(pThis);
1005
1006 RT_NOREF(pThis);
1007
1008 return (int64_t)RTTimeNanoTS();
1009}
1010
1011/**
1012 * Callback called by slirp to create a new timer and insert it into the given list.
1013 *
1014 * @param slirpTimeCb Callback function supplied to the new timer upon timer expiry.
1015 * Called later by the timeout handler.
1016 * @param cb_opaque Opaque object supplied to slirpTimeCb when called. Should be
1017 * Identical to the opaque parameter.
1018 * @param opaque Pointer to NAT State context.
1019 *
1020 * @returns Pointer to new timer.
1021 */
1022static DECLCALLBACK(void *) drvNAT_TimerNewCb(SlirpTimerCb slirpTimeCb, void *cb_opaque, void *opaque)
1023{
1024 PDRVNAT pThis = (PDRVNAT)opaque;
1025 Assert(pThis);
1026
1027 SlirpTimer *pNewTimer = (SlirpTimer *)RTMemAlloc(sizeof(SlirpTimer));
1028 if (!pNewTimer)
1029 return NULL;
1030
1031 pNewTimer->next = pThis->pNATState->pTimerHead;
1032 pNewTimer->uTimeExpire = -1;
1033 pNewTimer->pHandler = slirpTimeCb;
1034 pNewTimer->opaque = cb_opaque;
1035 pThis->pNATState->pTimerHead = pNewTimer;
1036
1037 return pNewTimer;
1038}
1039
1040/**
1041 * Callback called by slirp to free a timer.
1042 *
1043 * @param pTimer Pointer to slirpTimer object to be freed.
1044 * @param opaque Pointer to NAT State context.
1045 */
1046static DECLCALLBACK(void) drvNAT_TimerFreeCb(void *pTimer, void *opaque)
1047{
1048 PDRVNAT pThis = (PDRVNAT)opaque;
1049 Assert(pThis);
1050 SlirpTimer *pCurrent = pThis->pNATState->pTimerHead;
1051
1052 while (pCurrent != NULL)
1053 {
1054 if (pCurrent == (SlirpTimer *)pTimer)
1055 {
1056 SlirpTimer *pTmp = pCurrent->next;
1057 RTMemFree(pCurrent);
1058 pCurrent = pTmp;
1059 }
1060 else
1061 pCurrent = pCurrent->next;
1062 }
1063}
1064
1065/**
1066 * Callback called by slirp to modify a timer.
1067 *
1068 * @param pTimer Pointer to slirpTimer object to be modified.
1069 * @param expireTime Signed 64-bit integer representing the new expiry time.
1070 * @param opaque Pointer to NAT State context.
1071 */
1072static DECLCALLBACK(void) drvNAT_TimerModCb(void *pTimer, int64_t expireTime, void *opaque)
1073{
1074 PDRVNAT pThis = (PDRVNAT)opaque;
1075 Assert(pThis);
1076
1077 RT_NOREF(pThis);
1078
1079 ((SlirpTimer *)pTimer)->uTimeExpire = expireTime;
1080}
1081
1082/**
1083 * Callback called by slirp when there is I/O that needs to happen.
1084 *
1085 * @param opaque Pointer to NAT State context.
1086 */
1087static DECLCALLBACK(void) drvNAT_NotifyCb(void *opaque)
1088{
1089 PDRVNAT pThis = (PDRVNAT)opaque;
1090
1091 drvNATAsyncIoWakeup(pThis->pDrvIns, NULL);
1092}
1093
1094/**
1095 * Registers poll. Unused function (other than logging).
1096 */
1097static DECLCALLBACK(void) drvNAT_RegisterPoll(int fd, void *opaque) {
1098 RT_NOREF(fd, opaque);
1099 Log4(("Poll registered\n"));
1100}
1101
1102/**
1103 * Unregisters poll. Unused function (other than logging).
1104 */
1105static DECLCALLBACK(void) drvNAT_UnregisterPoll(int fd, void *opaque) {
1106 RT_NOREF(fd, opaque);
1107 Log4(("Poll unregistered\n"));
1108}
1109
1110/**
1111 * Callback function to add entry to pollfd array.
1112 *
1113 * @param iFd Integer of system file descriptor of socket.
1114 * (on windows, this is a VBox internal, not system, value).
1115 * @param iEvents Integer of slirp type poll events.
1116 * @param opaque Pointer to NAT State context.
1117 *
1118 * @returns Index of latest pollfd entry.
1119 *
1120 * @thread ?
1121 */
1122static DECLCALLBACK(int) drvNAT_AddPollCb(int iFd, int iEvents, void *opaque)
1123{
1124 PDRVNAT pThis = (PDRVNAT)opaque;
1125
1126 if (pThis->pNATState->nsock + 1 >= pThis->pNATState->uPollCap)
1127 {
1128 int cbNew = pThis->pNATState->uPollCap * 2 * sizeof(struct pollfd);
1129 struct pollfd *pvNew = (struct pollfd *)RTMemRealloc(pThis->pNATState->polls, cbNew);
1130 if(pvNew)
1131 {
1132 pThis->pNATState->polls = pvNew;
1133 pThis->pNATState->uPollCap *= 2;
1134 }
1135 else
1136 return -1;
1137 }
1138
1139 int idx = pThis->pNATState->nsock;
1140#ifdef RT_OS_WINDOWS
1141 pThis->pNATState->polls[idx].fd = libslirp_wrap_RTHandleTableLookup(iFd);
1142#else
1143 pThis->pNATState->polls[idx].fd = iFd;
1144#endif
1145 pThis->pNATState->polls[idx].events = drvNAT_PollEventSlirpToHost(iEvents);
1146 pThis->pNATState->polls[idx].revents = 0;
1147 pThis->pNATState->nsock += 1;
1148 return idx;
1149}
1150
1151/**
1152 * Get translated revents from a poll at a given index.
1153 *
1154 * @param idx Integer index of poll.
1155 * @param opaque Pointer to NAT State context.
1156 *
1157 * @returns Integer representing transalted revents.
1158 *
1159 * @thread ?
1160 */
1161static DECLCALLBACK(int) drvNAT_GetREventsCb(int idx, void *opaque)
1162{
1163 PDRVNAT pThis = (PDRVNAT)opaque;
1164 struct pollfd* polls = pThis->pNATState->polls;
1165 return drvNAT_PollEventHostToSlirp(polls[idx].revents);
1166}
1167
1168/**
1169 * Contructor/Destructor
1170 */
1171/**
1172 * Destruct a driver instance.
1173 *
1174 * Most VM resources are freed by the VM. This callback is provided so that any non-VM
1175 * resources can be freed correctly.
1176 *
1177 * @param pDrvIns The driver instance data.
1178 */
1179static DECLCALLBACK(void) drvNATDestruct(PPDMDRVINS pDrvIns)
1180{
1181 PDRVNAT pThis = PDMINS_2_DATA(pDrvIns, PDRVNAT);
1182 LogFlow(("drvNATDestruct:\n"));
1183 PDMDRV_CHECK_VERSIONS_RETURN_VOID(pDrvIns);
1184
1185 if (pThis->pNATState)
1186 {
1187 slirp_cleanup(pThis->pNATState->pSlirp);
1188#ifdef VBOX_WITH_STATISTICS
1189# define DRV_PROFILE_COUNTER(name, dsc) DEREGISTER_COUNTER(name, pThis)
1190# define DRV_COUNTING_COUNTER(name, dsc) DEREGISTER_COUNTER(name, pThis)
1191# include "slirp/counters.h"
1192#endif
1193 pThis->pNATState = NULL;
1194 }
1195
1196 RTReqQueueDestroy(pThis->hSlirpReqQueue);
1197 pThis->hSlirpReqQueue = NIL_RTREQQUEUE;
1198
1199 RTReqQueueDestroy(pThis->hRecvReqQueue);
1200 pThis->hRecvReqQueue = NIL_RTREQQUEUE;
1201
1202 RTSemEventDestroy(pThis->EventRecv);
1203 pThis->EventRecv = NIL_RTSEMEVENT;
1204
1205 if (RTCritSectIsInitialized(&pThis->DevAccessLock))
1206 RTCritSectDelete(&pThis->DevAccessLock);
1207
1208 if (RTCritSectIsInitialized(&pThis->XmitLock))
1209 RTCritSectDelete(&pThis->XmitLock);
1210
1211#ifndef RT_OS_WINDOWS
1212 RTPipeClose(pThis->hPipeRead);
1213 RTPipeClose(pThis->hPipeWrite);
1214#endif
1215}
1216
1217/**
1218 * Construct a NAT network transport driver instance.
1219 *
1220 * @copydoc FNPDMDRVCONSTRUCT
1221 */
1222static DECLCALLBACK(int) drvNATConstruct(PPDMDRVINS pDrvIns, PCFGMNODE pCfg, uint32_t fFlags)
1223{
1224 int rc = 0;
1225
1226 /* Construct PDRVNAT */
1227
1228 RT_NOREF(fFlags);
1229 PDMDRV_CHECK_VERSIONS_RETURN(pDrvIns);
1230 PDRVNAT pThis = PDMINS_2_DATA(pDrvIns, PDRVNAT);
1231
1232 /*
1233 * Init the static parts.
1234 */
1235 pThis->pDrvIns = pDrvIns;
1236 pThis->pNATState = (SlirpState *)RTMemAlloc(sizeof(SlirpState));
1237 if(pThis->pNATState == NULL)
1238 return VERR_NO_MEMORY;
1239 else
1240 {
1241 pThis->pNATState->nsock = 0;
1242 pThis->pNATState->pTimerHead = NULL;
1243 pThis->pNATState->polls = (struct pollfd *)RTMemAlloc(64 * sizeof(struct pollfd));
1244 pThis->pNATState->uPollCap = 64;
1245 }
1246 pThis->hSlirpReqQueue = NIL_RTREQQUEUE;
1247 pThis->EventRecv = NIL_RTSEMEVENT;
1248
1249 /* IBase */
1250 pDrvIns->IBase.pfnQueryInterface = drvNATQueryInterface;
1251
1252 /* INetwork */
1253 pThis->INetworkUp.pfnBeginXmit = drvNATNetworkUp_BeginXmit;
1254 pThis->INetworkUp.pfnAllocBuf = drvNATNetworkUp_AllocBuf;
1255 pThis->INetworkUp.pfnFreeBuf = drvNATNetworkUp_FreeBuf;
1256 pThis->INetworkUp.pfnSendBuf = drvNATNetworkUp_SendBuf;
1257 pThis->INetworkUp.pfnEndXmit = drvNATNetworkUp_EndXmit;
1258 pThis->INetworkUp.pfnSetPromiscuousMode = drvNATNetworkUp_SetPromiscuousMode;
1259 pThis->INetworkUp.pfnNotifyLinkChanged = drvNATNetworkUp_NotifyLinkChanged;
1260
1261 /* NAT engine configuration */
1262 pThis->INetworkNATCfg.pfnRedirectRuleCommand = drvNATNetworkNatConfigRedirect;
1263 pThis->INetworkNATCfg.pfnNotifyDnsChanged = NULL;
1264
1265 /*
1266 * Validate the config.
1267 */
1268 PDMDRV_VALIDATE_CONFIG_RETURN(pDrvIns,
1269 "PassDomain"
1270 "|TFTPPrefix"
1271 "|BootFile"
1272 "|Network"
1273 "|NextServer"
1274 "|DNSProxy"
1275 "|BindIP"
1276 "|UseHostResolver"
1277 "|SlirpMTU"
1278 "|AliasMode"
1279 "|SockRcv"
1280 "|SockSnd"
1281 "|TcpRcv"
1282 "|TcpSnd"
1283 "|ICMPCacheLimit"
1284 "|SoMaxConnection"
1285 "|LocalhostReachable"
1286 "|HostResolverMappings"
1287 , "PortForwarding");
1288
1289 /*
1290 * Get the configuration settings.
1291 */
1292 bool fPassDomain = true;
1293 GET_BOOL(rc, pDrvIns, pCfg, "PassDomain", fPassDomain);
1294
1295 GET_STRING_ALLOC(rc, pDrvIns, pCfg, "TFTPPrefix", pThis->pszTFTPPrefix);
1296 GET_STRING_ALLOC(rc, pDrvIns, pCfg, "BootFile", pThis->pszBootFile);
1297 GET_STRING_ALLOC(rc, pDrvIns, pCfg, "NextServer", pThis->pszNextServer);
1298
1299 int fDNSProxy = 0;
1300 GET_S32(rc, pDrvIns, pCfg, "DNSProxy", fDNSProxy);
1301 int MTU = 1500;
1302 GET_S32(rc, pDrvIns, pCfg, "SlirpMTU", MTU);
1303 int i32AliasMode = 0;
1304 int i32MainAliasMode = 0;
1305 GET_S32(rc, pDrvIns, pCfg, "AliasMode", i32MainAliasMode);
1306 int iIcmpCacheLimit = 100;
1307 GET_S32(rc, pDrvIns, pCfg, "ICMPCacheLimit", iIcmpCacheLimit);
1308 bool fLocalhostReachable = false;
1309 GET_BOOL(rc, pDrvIns, pCfg, "LocalhostReachable", fLocalhostReachable);
1310
1311 i32AliasMode |= (i32MainAliasMode & 0x1 ? 0x1 : 0);
1312 i32AliasMode |= (i32MainAliasMode & 0x2 ? 0x40 : 0);
1313 i32AliasMode |= (i32MainAliasMode & 0x4 ? 0x4 : 0);
1314 int i32SoMaxConn = 10;
1315 GET_S32(rc, pDrvIns, pCfg, "SoMaxConnection", i32SoMaxConn);
1316 /*
1317 * Query the network port interface.
1318 */
1319 pThis->pIAboveNet = PDMIBASE_QUERY_INTERFACE(pDrvIns->pUpBase, PDMINETWORKDOWN);
1320 if (!pThis->pIAboveNet)
1321 return PDMDRV_SET_ERROR(pDrvIns, VERR_PDM_MISSING_INTERFACE_ABOVE,
1322 N_("Configuration error: the above device/driver didn't "
1323 "export the network port interface"));
1324 pThis->pIAboveConfig = PDMIBASE_QUERY_INTERFACE(pDrvIns->pUpBase, PDMINETWORKCONFIG);
1325 if (!pThis->pIAboveConfig)
1326 return PDMDRV_SET_ERROR(pDrvIns, VERR_PDM_MISSING_INTERFACE_ABOVE,
1327 N_("Configuration error: the above device/driver didn't "
1328 "export the network config interface"));
1329
1330 /* Generate a network address for this network card. */
1331 char szNetwork[32]; /* xxx.xxx.xxx.xxx/yy */
1332 GET_STRING(rc, pDrvIns, pCfg, "Network", szNetwork[0], sizeof(szNetwork));
1333 if (rc == VERR_CFGM_VALUE_NOT_FOUND)
1334 return PDMDrvHlpVMSetError(pDrvIns, rc, RT_SRC_POS, N_("NAT%d: Configuration error: missing network"),
1335 pDrvIns->iInstance);
1336
1337 RTNETADDRIPV4 Network, Netmask;
1338
1339 rc = RTCidrStrToIPv4(szNetwork, &Network, &Netmask);
1340 if (RT_FAILURE(rc))
1341 return PDMDrvHlpVMSetError(pDrvIns, rc, RT_SRC_POS,
1342 N_("NAT#%d: Configuration error: network '%s' describes not a valid IPv4 network"),
1343 pDrvIns->iInstance, szNetwork);
1344
1345 /* Construct Libslirp Config and Initialzie Slirp */
1346
1347 LogFlow(("Here is what is coming out of the vbox config:\n \
1348 Network: %lu\n \
1349 Netmask: %lu\n", Network, Netmask));
1350
1351#ifndef RT_OS_WINDOWS
1352 struct in_addr vnetwork = RTNetIPv4AddrHEToInAddr(&Network);
1353 struct in_addr vnetmask = RTNetIPv4AddrHEToInAddr(&Netmask);
1354 struct in_addr vhost = RTNetInAddrFromU8(10, 0, 2, 2);
1355 struct in_addr vdhcp_start = RTNetInAddrFromU8(10, 0, 2, 15);
1356 struct in_addr vnameserver = RTNetInAddrFromU8(10, 0, 2, 3);
1357#else
1358 struct in_addr vnetwork;
1359 vnetwork.S_un.S_addr = RT_BSWAP_U32(Network.u);
1360
1361 struct in_addr vnetmask;
1362 vnetmask.S_un.S_addr = RT_BSWAP_U32(Netmask.u);
1363
1364 struct in_addr vhost;
1365 vhost.S_un.S_addr = RT_BSWAP_U32(0x0a000202);
1366
1367 struct in_addr vdhcp_start;
1368 vdhcp_start.S_un.S_addr = RT_BSWAP_U32(0x0a00020f);
1369
1370 struct in_addr vnameserver;
1371 vnameserver.S_un.S_addr = RT_BSWAP_U32(0x0a000203);
1372#endif
1373
1374 SlirpConfig *pSlirpCfg = new SlirpConfig { 0 };
1375
1376 pSlirpCfg->version = 4;
1377 pSlirpCfg->restricted = false;
1378 pSlirpCfg->in_enabled = true;
1379 pSlirpCfg->vnetwork = vnetwork;
1380 pSlirpCfg->vnetmask = vnetmask;
1381 pSlirpCfg->vhost = vhost;
1382 pSlirpCfg->in6_enabled = true;
1383
1384 inet_pton(AF_INET6, "fd00::", &pSlirpCfg->vprefix_addr6);
1385 pSlirpCfg->vprefix_len = 64;
1386 inet_pton(AF_INET6, "fd00::2", &pSlirpCfg->vhost6);
1387
1388 pSlirpCfg->vhostname = "vbox";
1389 pSlirpCfg->tftp_server_name = pThis->pszNextServer;
1390 pSlirpCfg->tftp_path = pThis->pszTFTPPrefix;
1391 pSlirpCfg->bootfile = pThis->pszBootFile;
1392 pSlirpCfg->vdhcp_start = vdhcp_start;
1393 pSlirpCfg->vnameserver = vnameserver;
1394 pSlirpCfg->if_mtu = MTU;
1395
1396 inet_pton(AF_INET6, "fd00::3", &pSlirpCfg->vnameserver6);
1397
1398 pSlirpCfg->vdnssearch = NULL;
1399 pSlirpCfg->vdomainname = NULL;
1400
1401 SlirpCb *slirpCallbacks = (struct SlirpCb *)RTMemAlloc(sizeof(SlirpCb));
1402
1403 slirpCallbacks->send_packet = &drvNAT_SendPacketCb;
1404 slirpCallbacks->guest_error = &drvNAT_GuestErrorCb;
1405 slirpCallbacks->clock_get_ns = &drvNAT_ClockGetNsCb;
1406 slirpCallbacks->timer_new = &drvNAT_TimerNewCb;
1407 slirpCallbacks->timer_free = &drvNAT_TimerFreeCb;
1408 slirpCallbacks->timer_mod = &drvNAT_TimerModCb;
1409 slirpCallbacks->register_poll_fd = &drvNAT_RegisterPoll;
1410 slirpCallbacks->unregister_poll_fd = &drvNAT_UnregisterPoll;
1411 slirpCallbacks->notify = &drvNAT_NotifyCb;
1412 slirpCallbacks->init_completed = NULL;
1413 slirpCallbacks->timer_new_opaque = NULL;
1414
1415 Slirp *pSlirp = slirp_new(/* cfg */ pSlirpCfg, /* callbacks */ slirpCallbacks, /* opaque */ pThis);
1416
1417 if (pSlirp == NULL)
1418 return VERR_INVALID_POINTER;
1419
1420 pThis->pNATState->pSlirp = pSlirp;
1421
1422 rc = drvNATConstructRedir(pDrvIns->iInstance, pThis, pCfg, &Network);
1423 AssertLogRelRCReturn(rc, rc);
1424
1425 rc = PDMDrvHlpSSMRegisterLoadDone(pDrvIns, NULL);
1426 AssertLogRelRCReturn(rc, rc);
1427
1428 rc = RTReqQueueCreate(&pThis->hSlirpReqQueue);
1429 AssertLogRelRCReturn(rc, rc);
1430
1431 rc = RTReqQueueCreate(&pThis->hRecvReqQueue);
1432 AssertLogRelRCReturn(rc, rc);
1433
1434 rc = PDMDrvHlpThreadCreate(pDrvIns, &pThis->pRecvThread, pThis, drvNATRecv,
1435 drvNATRecvWakeup, 256 * _1K, RTTHREADTYPE_IO, "NATRX");
1436 AssertRCReturn(rc, rc);
1437
1438 rc = RTSemEventCreate(&pThis->EventRecv);
1439 AssertRCReturn(rc, rc);
1440
1441 rc = RTCritSectInit(&pThis->DevAccessLock);
1442 AssertRCReturn(rc, rc);
1443
1444 rc = RTCritSectInit(&pThis->XmitLock);
1445 AssertRCReturn(rc, rc);
1446
1447 char szTmp[128];
1448 RTStrPrintf(szTmp, sizeof(szTmp), "nat%d", pDrvIns->iInstance);
1449 PDMDrvHlpDBGFInfoRegister(pDrvIns, szTmp, "NAT info.", drvNATInfo);
1450
1451#ifdef VBOX_WITH_STATISTICS
1452# define DRV_PROFILE_COUNTER(name, dsc) REGISTER_COUNTER(name, pThis, STAMTYPE_PROFILE, STAMUNIT_TICKS_PER_CALL, dsc)
1453# define DRV_COUNTING_COUNTER(name, dsc) REGISTER_COUNTER(name, pThis, STAMTYPE_COUNTER, STAMUNIT_COUNT, dsc)
1454# include "slirp/counters.h"
1455#endif
1456
1457#ifndef RT_OS_WINDOWS
1458 /**
1459 * Create the control pipe.
1460 */
1461 rc = RTPipeCreate(&pThis->hPipeRead, &pThis->hPipeWrite, 0 /*fFlags*/);
1462 AssertRCReturn(rc, rc);
1463#endif
1464
1465 rc = PDMDrvHlpThreadCreate(pDrvIns, &pThis->pSlirpThread, pThis, drvNATAsyncIoThread,
1466 drvNATAsyncIoWakeup, 256 * _1K, RTTHREADTYPE_IO, "NAT");
1467 AssertRCReturn(rc, rc);
1468
1469 pThis->enmLinkState = pThis->enmLinkStateWant = PDMNETWORKLINKSTATE_UP;
1470
1471 return rc;
1472}
1473
1474/**
1475 * NAT network transport driver registration record.
1476 */
1477const PDMDRVREG g_DrvNATlibslirp =
1478{
1479 /* u32Version */
1480 PDM_DRVREG_VERSION,
1481 /* szName */
1482 "NAT",
1483 /* szRCMod */
1484 "",
1485 /* szR0Mod */
1486 "",
1487 /* pszDescription */
1488 "NATlibslrip Network Transport Driver",
1489 /* fFlags */
1490 PDM_DRVREG_FLAGS_HOST_BITS_DEFAULT,
1491 /* fClass. */
1492 PDM_DRVREG_CLASS_NETWORK,
1493 /* cMaxInstances */
1494 ~0U,
1495 /* cbInstance */
1496 sizeof(DRVNAT),
1497 /* pfnConstruct */
1498 drvNATConstruct,
1499 /* pfnDestruct */
1500 drvNATDestruct,
1501 /* pfnRelocate */
1502 NULL,
1503 /* pfnIOCtl */
1504 NULL,
1505 /* pfnPowerOn */
1506 NULL,
1507 /* pfnReset */
1508 NULL,
1509 /* pfnSuspend */
1510 NULL,
1511 /* pfnResume */
1512 NULL,
1513 /* pfnAttach */
1514 NULL,
1515 /* pfnDetach */
1516 NULL,
1517 /* pfnPowerOff */
1518 NULL,
1519 /* pfnSoftReset */
1520 NULL,
1521 /* u32EndVersion */
1522 PDM_DRVREG_VERSION
1523};
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