VirtualBox

source: vbox/trunk/src/VBox/Devices/Network/DrvNAT.cpp@ 34244

Last change on this file since 34244 was 34209, checked in by vboxsync, 14 years ago

NAT: added 'info nat%d' handler

  • Property svn:eol-style set to native
  • Property svn:keywords set to Author Date Id Revision
File size: 49.3 KB
Line 
1/* $Id: DrvNAT.cpp 34209 2010-11-19 16:04:55Z vboxsync $ */
2/** @file
3 * DrvNAT - NAT network transport driver.
4 */
5
6/*
7 * Copyright (C) 2006-2010 Oracle Corporation
8 *
9 * This file is part of VirtualBox Open Source Edition (OSE), as
10 * available from http://www.virtualbox.org. This file is free software;
11 * you can redistribute it and/or modify it under the terms of the GNU
12 * General Public License (GPL) as published by the Free Software
13 * Foundation, in version 2 as it comes in the "COPYING" file of the
14 * VirtualBox OSE distribution. VirtualBox OSE is distributed in the
15 * hope that it will be useful, but WITHOUT ANY WARRANTY of any kind.
16 */
17
18
19/*******************************************************************************
20* Header Files *
21*******************************************************************************/
22#define LOG_GROUP LOG_GROUP_DRV_NAT
23#define __STDC_LIMIT_MACROS
24#define __STDC_CONSTANT_MACROS
25#include "slirp/libslirp.h"
26#include "slirp/ctl.h"
27#include <VBox/pdmdrv.h>
28#include <VBox/pdmnetifs.h>
29#include <VBox/pdmnetinline.h>
30#include <iprt/assert.h>
31#include <iprt/file.h>
32#include <iprt/mem.h>
33#include <iprt/string.h>
34#include <iprt/critsect.h>
35#include <iprt/cidr.h>
36#include <iprt/stream.h>
37#include <iprt/uuid.h>
38
39#include "Builtins.h"
40
41#ifndef RT_OS_WINDOWS
42# include <unistd.h>
43# include <fcntl.h>
44# include <poll.h>
45# include <errno.h>
46#endif
47#ifdef RT_OS_FREEBSD
48# include <netinet/in.h>
49#endif
50#include <iprt/semaphore.h>
51#include <iprt/req.h>
52
53#define COUNTERS_INIT
54#include "counters.h"
55
56
57/*******************************************************************************
58* Defined Constants And Macros *
59*******************************************************************************/
60
61/**
62 * @todo: This is a bad hack to prevent freezing the guest during high network
63 * activity. Windows host only. This needs to be fixed properly.
64 */
65#define VBOX_NAT_DELAY_HACK
66
67#define GET_EXTRADATA(pthis, node, name, rc, type, type_name, var) \
68do { \
69 (rc) = CFGMR3Query ## type((node), name, &(var)); \
70 if (RT_FAILURE((rc)) && (rc) != VERR_CFGM_VALUE_NOT_FOUND) \
71 return PDMDrvHlpVMSetError((pthis)->pDrvIns, (rc), RT_SRC_POS, N_("NAT#%d: configuration query for \""name"\" " #type_name " failed"), \
72 (pthis)->pDrvIns->iInstance); \
73} while (0)
74
75#define GET_ED_STRICT(pthis, node, name, rc, type, type_name, var) \
76do { \
77 (rc) = CFGMR3Query ## type((node), name, &(var)); \
78 if (RT_FAILURE((rc))) \
79 return PDMDrvHlpVMSetError((pthis)->pDrvIns, (rc), RT_SRC_POS, N_("NAT#%d: configuration query for \""name"\" " #type_name " failed"), \
80 (pthis)->pDrvIns->iInstance); \
81} while (0)
82
83#define GET_EXTRADATA_N(pthis, node, name, rc, type, type_name, var, var_size) \
84do { \
85 (rc) = CFGMR3Query ## type((node), name, &(var), var_size); \
86 if (RT_FAILURE((rc)) && (rc) != VERR_CFGM_VALUE_NOT_FOUND) \
87 return PDMDrvHlpVMSetError((pthis)->pDrvIns, (rc), RT_SRC_POS, N_("NAT#%d: configuration query for \""name"\" " #type_name " failed"), \
88 (pthis)->pDrvIns->iInstance); \
89} while (0)
90
91#define GET_BOOL(rc, pthis, node, name, var) \
92 GET_EXTRADATA(pthis, node, name, (rc), Bool, bolean, (var))
93#define GET_STRING(rc, pthis, node, name, var, var_size) \
94 GET_EXTRADATA_N(pthis, node, name, (rc), String, string, (var), (var_size))
95#define GET_STRING_ALLOC(rc, pthis, node, name, var) \
96 GET_EXTRADATA(pthis, node, name, (rc), StringAlloc, string, (var))
97#define GET_S32(rc, pthis, node, name, var) \
98 GET_EXTRADATA(pthis, node, name, (rc), S32, int, (var))
99#define GET_S32_STRICT(rc, pthis, node, name, var) \
100 GET_ED_STRICT(pthis, node, name, (rc), S32, int, (var))
101
102
103
104#define DO_GET_IP(rc, node, instance, status, x) \
105do { \
106 char sz##x[32]; \
107 GET_STRING((rc), (node), (instance), #x, sz ## x[0], sizeof(sz ## x)); \
108 if (rc != VERR_CFGM_VALUE_NOT_FOUND) \
109 (status) = inet_aton(sz ## x, &x); \
110} while (0)
111
112#define GETIP_DEF(rc, node, instance, x, def) \
113do \
114{ \
115 int status = 0; \
116 DO_GET_IP((rc), (node), (instance), status, x); \
117 if (status == 0 || rc == VERR_CFGM_VALUE_NOT_FOUND) \
118 x.s_addr = def; \
119} while (0)
120
121/*******************************************************************************
122* Structures and Typedefs *
123*******************************************************************************/
124/**
125 * NAT network transport driver instance data.
126 *
127 * @implements PDMINETWORKUP
128 */
129typedef struct DRVNAT
130{
131 /** The network interface. */
132 PDMINETWORKUP INetworkUp;
133 /** The network NAT Engine configureation. */
134 PDMINETWORKNATCONFIG INetworkNATCfg;
135 /** The port we're attached to. */
136 PPDMINETWORKDOWN pIAboveNet;
137 /** The network config of the port we're attached to. */
138 PPDMINETWORKCONFIG pIAboveConfig;
139 /** Pointer to the driver instance. */
140 PPDMDRVINS pDrvIns;
141 /** Link state */
142 PDMNETWORKLINKSTATE enmLinkState;
143 /** NAT state for this instance. */
144 PNATState pNATState;
145 /** TFTP directory prefix. */
146 char *pszTFTPPrefix;
147 /** Boot file name to provide in the DHCP server response. */
148 char *pszBootFile;
149 /** tftp server name to provide in the DHCP server response. */
150 char *pszNextServer;
151 /** Polling thread. */
152 PPDMTHREAD pSlirpThread;
153 /** Queue for NAT-thread-external events. */
154 PRTREQQUEUE pSlirpReqQueue;
155 /** The guest IP for port-forwarding. */
156 uint32_t GuestIP;
157 /** Link state set when the VM is suspended. */
158 PDMNETWORKLINKSTATE enmLinkStateWant;
159
160#ifdef VBOX_WITH_SLIRP_MT
161 PPDMTHREAD pGuestThread;
162#endif
163#ifndef RT_OS_WINDOWS
164 /** The write end of the control pipe. */
165 RTFILE PipeWrite;
166 /** The read end of the control pipe. */
167 RTFILE PipeRead;
168#else
169 /** for external notification */
170 HANDLE hWakeupEvent;
171#endif
172
173#define DRV_PROFILE_COUNTER(name, dsc) STAMPROFILE Stat ## name
174#define DRV_COUNTING_COUNTER(name, dsc) STAMCOUNTER Stat ## name
175#include "counters.h"
176 /** thread delivering packets for receiving by the guest */
177 PPDMTHREAD pRecvThread;
178 /** thread delivering urg packets for receiving by the guest */
179 PPDMTHREAD pUrgRecvThread;
180 /** event to wakeup the guest receive thread */
181 RTSEMEVENT EventRecv;
182 /** event to wakeup the guest urgent receive thread */
183 RTSEMEVENT EventUrgRecv;
184 /** Receive Req queue (deliver packets to the guest) */
185 PRTREQQUEUE pRecvReqQueue;
186 /** Receive Urgent Req queue (deliver packets to the guest). */
187 PRTREQQUEUE pUrgRecvReqQueue;
188
189 /** makes access to device func RecvAvail and Recv atomical. */
190 RTCRITSECT DevAccessLock;
191 /** Number of in-flight urgent packets. */
192 volatile uint32_t cUrgPkts;
193 /** Number of in-flight regular packets. */
194 volatile uint32_t cPkts;
195
196 /** Transmit lock taken by BeginXmit and released by EndXmit. */
197 RTCRITSECT XmitLock;
198} DRVNAT;
199AssertCompileMemberAlignment(DRVNAT, StatNATRecvWakeups, 8);
200/** Pointer the NAT driver instance data. */
201typedef DRVNAT *PDRVNAT;
202
203
204/*******************************************************************************
205* Internal Functions *
206*******************************************************************************/
207static void drvNATNotifyNATThread(PDRVNAT pThis, const char *pszWho);
208
209
210static DECLCALLBACK(int) drvNATRecv(PPDMDRVINS pDrvIns, PPDMTHREAD pThread)
211{
212 PDRVNAT pThis = PDMINS_2_DATA(pDrvIns, PDRVNAT);
213
214 if (pThread->enmState == PDMTHREADSTATE_INITIALIZING)
215 return VINF_SUCCESS;
216
217 while (pThread->enmState == PDMTHREADSTATE_RUNNING)
218 {
219 RTReqProcess(pThis->pRecvReqQueue, 0);
220 if (ASMAtomicReadU32(&pThis->cPkts) == 0)
221 RTSemEventWait(pThis->EventRecv, RT_INDEFINITE_WAIT);
222 }
223 return VINF_SUCCESS;
224}
225
226
227static DECLCALLBACK(int) drvNATRecvWakeup(PPDMDRVINS pDrvIns, PPDMTHREAD pThread)
228{
229 PDRVNAT pThis = PDMINS_2_DATA(pDrvIns, PDRVNAT);
230 int rc;
231 rc = RTSemEventSignal(pThis->EventRecv);
232
233 STAM_COUNTER_INC(&pThis->StatNATRecvWakeups);
234 return VINF_SUCCESS;
235}
236
237static DECLCALLBACK(int) drvNATUrgRecv(PPDMDRVINS pDrvIns, PPDMTHREAD pThread)
238{
239 PDRVNAT pThis = PDMINS_2_DATA(pDrvIns, PDRVNAT);
240
241 if (pThread->enmState == PDMTHREADSTATE_INITIALIZING)
242 return VINF_SUCCESS;
243
244 while (pThread->enmState == PDMTHREADSTATE_RUNNING)
245 {
246 RTReqProcess(pThis->pUrgRecvReqQueue, 0);
247 if (ASMAtomicReadU32(&pThis->cUrgPkts) == 0)
248 {
249 int rc = RTSemEventWait(pThis->EventUrgRecv, RT_INDEFINITE_WAIT);
250 AssertRC(rc);
251 }
252 }
253 return VINF_SUCCESS;
254}
255
256static DECLCALLBACK(int) drvNATUrgRecvWakeup(PPDMDRVINS pDrvIns, PPDMTHREAD pThread)
257{
258 PDRVNAT pThis = PDMINS_2_DATA(pDrvIns, PDRVNAT);
259 int rc = RTSemEventSignal(pThis->EventUrgRecv);
260 AssertRC(rc);
261
262 return VINF_SUCCESS;
263}
264
265static DECLCALLBACK(void) drvNATUrgRecvWorker(PDRVNAT pThis, uint8_t *pu8Buf, int cb, struct mbuf *m)
266{
267 int rc = RTCritSectEnter(&pThis->DevAccessLock);
268 AssertRC(rc);
269 rc = pThis->pIAboveNet->pfnWaitReceiveAvail(pThis->pIAboveNet, RT_INDEFINITE_WAIT);
270 if (RT_SUCCESS(rc))
271 {
272 rc = pThis->pIAboveNet->pfnReceive(pThis->pIAboveNet, pu8Buf, cb);
273 AssertRC(rc);
274 }
275 else if ( rc != VERR_TIMEOUT
276 && rc != VERR_INTERRUPTED)
277 {
278 AssertRC(rc);
279 }
280
281 rc = RTCritSectLeave(&pThis->DevAccessLock);
282 AssertRC(rc);
283
284 slirp_ext_m_free(pThis->pNATState, m, pu8Buf);
285 if (ASMAtomicDecU32(&pThis->cUrgPkts) == 0)
286 {
287 drvNATRecvWakeup(pThis->pDrvIns, pThis->pRecvThread);
288 drvNATNotifyNATThread(pThis, "drvNATUrgRecvWorker");
289 }
290}
291
292
293static DECLCALLBACK(void) drvNATRecvWorker(PDRVNAT pThis, uint8_t *pu8Buf, int cb, struct mbuf *m)
294{
295 int rc;
296 STAM_PROFILE_START(&pThis->StatNATRecv, a);
297
298 STAM_PROFILE_START(&pThis->StatNATRecvWait, b);
299
300 while (ASMAtomicReadU32(&pThis->cUrgPkts) != 0)
301 {
302 rc = RTSemEventWait(pThis->EventRecv, RT_INDEFINITE_WAIT);
303 if ( RT_FAILURE(rc)
304 && ( rc == VERR_TIMEOUT
305 || rc == VERR_INTERRUPTED))
306 goto done_unlocked;
307 }
308
309 rc = RTCritSectEnter(&pThis->DevAccessLock);
310 AssertRC(rc);
311
312 rc = pThis->pIAboveNet->pfnWaitReceiveAvail(pThis->pIAboveNet, RT_INDEFINITE_WAIT);
313 if (RT_SUCCESS(rc))
314 {
315 rc = pThis->pIAboveNet->pfnReceive(pThis->pIAboveNet, pu8Buf, cb);
316 AssertRC(rc);
317 }
318 else if ( rc != VERR_TIMEOUT
319 && rc != VERR_INTERRUPTED)
320 {
321 AssertRC(rc);
322 }
323
324 rc = RTCritSectLeave(&pThis->DevAccessLock);
325 AssertRC(rc);
326
327done_unlocked:
328 slirp_ext_m_free(pThis->pNATState, m, pu8Buf);
329 ASMAtomicDecU32(&pThis->cPkts);
330
331 drvNATNotifyNATThread(pThis, "drvNATRecvWorker");
332
333 STAM_PROFILE_STOP(&pThis->StatNATRecvWait, b);
334 STAM_PROFILE_STOP(&pThis->StatNATRecv, a);
335}
336
337/**
338 * Frees a S/G buffer allocated by drvNATNetworkUp_AllocBuf.
339 *
340 * @param pThis Pointer to the NAT instance.
341 * @param pSgBuf The S/G buffer to free.
342 */
343static void drvNATFreeSgBuf(PDRVNAT pThis, PPDMSCATTERGATHER pSgBuf)
344{
345 Assert((pSgBuf->fFlags & PDMSCATTERGATHER_FLAGS_MAGIC_MASK) == PDMSCATTERGATHER_FLAGS_MAGIC);
346 pSgBuf->fFlags = 0;
347 if (pSgBuf->pvAllocator)
348 {
349 Assert(!pSgBuf->pvUser);
350 slirp_ext_m_free(pThis->pNATState, (struct mbuf *)pSgBuf->pvAllocator, NULL);
351 pSgBuf->pvAllocator = NULL;
352 }
353 else if (pSgBuf->pvUser)
354 {
355 RTMemFree(pSgBuf->aSegs[0].pvSeg);
356 pSgBuf->aSegs[0].pvSeg = NULL;
357 RTMemFree(pSgBuf->pvUser);
358 pSgBuf->pvUser = NULL;
359 }
360 RTMemFree(pSgBuf);
361}
362
363/**
364 * Worker function for drvNATSend().
365 *
366 * @param pThis Pointer to the NAT instance.
367 * @param pSgBuf The scatter/gather buffer.
368 * @thread NAT
369 */
370static void drvNATSendWorker(PDRVNAT pThis, PPDMSCATTERGATHER pSgBuf)
371{
372 Assert(pThis->enmLinkState == PDMNETWORKLINKSTATE_UP);
373 if (pThis->enmLinkState == PDMNETWORKLINKSTATE_UP)
374 {
375 struct mbuf *m = (struct mbuf *)pSgBuf->pvAllocator;
376 if (m)
377 {
378 /*
379 * A normal frame.
380 */
381 pSgBuf->pvAllocator = NULL;
382 slirp_input(pThis->pNATState, m, pSgBuf->cbUsed);
383 }
384 else
385 {
386 /*
387 * GSO frame, need to segment it.
388 */
389 /** @todo Make the NAT engine grok large frames? Could be more efficient... */
390#if 0 /* this is for testing PDMNetGsoCarveSegmentQD. */
391 uint8_t abHdrScratch[256];
392#endif
393 uint8_t const *pbFrame = (uint8_t const *)pSgBuf->aSegs[0].pvSeg;
394 PCPDMNETWORKGSO pGso = (PCPDMNETWORKGSO)pSgBuf->pvUser;
395 uint32_t const cSegs = PDMNetGsoCalcSegmentCount(pGso, pSgBuf->cbUsed); Assert(cSegs > 1);
396 for (size_t iSeg = 0; iSeg < cSegs; iSeg++)
397 {
398 size_t cbSeg;
399 void *pvSeg;
400 m = slirp_ext_m_get(pThis->pNATState, pGso->cbHdrs + pGso->cbMaxSeg, &pvSeg, &cbSeg);
401 if (!m)
402 break;
403
404#if 1
405 uint32_t cbPayload;
406 uint32_t offPayload = PDMNetGsoCarveSegment(pGso, pbFrame, pSgBuf->cbUsed,
407 iSeg, cSegs, (uint8_t *)pvSeg, &cbPayload);
408 memcpy((uint8_t *)pvSeg + pGso->cbHdrs, pbFrame + offPayload, cbPayload);
409
410 slirp_input(pThis->pNATState, m, cbPayload + pGso->cbHdrs);
411#else
412 uint32_t cbSegFrame;
413 void *pvSegFrame = PDMNetGsoCarveSegmentQD(pGso, (uint8_t *)pbFrame, pSgBuf->cbUsed, abHdrScratch,
414 iSeg, cSegs, &cbSegFrame);
415 memcpy((uint8_t *)pvSeg, pvSegFrame, cbSegFrame);
416
417 slirp_input(pThis->pNATState, m, cbSegFrame);
418#endif
419 }
420 }
421 }
422 drvNATFreeSgBuf(pThis, pSgBuf);
423
424 /** @todo Implement the VERR_TRY_AGAIN drvNATNetworkUp_AllocBuf semantics. */
425}
426
427/**
428 * @interface_method_impl{PDMINETWORKUP,pfnBeginXmit}
429 */
430static DECLCALLBACK(int) drvNATNetworkUp_BeginXmit(PPDMINETWORKUP pInterface, bool fOnWorkerThread)
431{
432 PDRVNAT pThis = RT_FROM_MEMBER(pInterface, DRVNAT, INetworkUp);
433 int rc = RTCritSectTryEnter(&pThis->XmitLock);
434 if (RT_FAILURE(rc))
435 {
436 /** @todo Kick the worker thread when we have one... */
437 rc = VERR_TRY_AGAIN;
438 }
439 return rc;
440}
441
442/**
443 * @interface_method_impl{PDMINETWORKUP,pfnAllocBuf}
444 */
445static DECLCALLBACK(int) drvNATNetworkUp_AllocBuf(PPDMINETWORKUP pInterface, size_t cbMin,
446 PCPDMNETWORKGSO pGso, PPPDMSCATTERGATHER ppSgBuf)
447{
448 PDRVNAT pThis = RT_FROM_MEMBER(pInterface, DRVNAT, INetworkUp);
449 Assert(RTCritSectIsOwner(&pThis->XmitLock));
450
451 /*
452 * Drop the incoming frame if the NAT thread isn't running.
453 */
454 if (pThis->pSlirpThread->enmState != PDMTHREADSTATE_RUNNING)
455 {
456 Log(("drvNATNetowrkUp_AllocBuf: returns VERR_NET_NO_NETWORK\n"));
457 return VERR_NET_NO_NETWORK;
458 }
459
460 /*
461 * Allocate a scatter/gather buffer and an mbuf.
462 */
463 PPDMSCATTERGATHER pSgBuf = (PPDMSCATTERGATHER)RTMemAlloc(sizeof(*pSgBuf));
464 if (!pSgBuf)
465 return VERR_NO_MEMORY;
466 if (!pGso)
467 {
468 pSgBuf->pvUser = NULL;
469 pSgBuf->pvAllocator = slirp_ext_m_get(pThis->pNATState, cbMin,
470 &pSgBuf->aSegs[0].pvSeg, &pSgBuf->aSegs[0].cbSeg);
471 if (!pSgBuf->pvAllocator)
472 {
473 RTMemFree(pSgBuf);
474 /** @todo Implement the VERR_TRY_AGAIN semantics. */
475 return VERR_NO_MEMORY;
476 }
477 }
478 else
479 {
480 pSgBuf->pvUser = RTMemDup(pGso, sizeof(*pGso));
481 pSgBuf->pvAllocator = NULL;
482 pSgBuf->aSegs[0].cbSeg = RT_ALIGN_Z(cbMin, 16);
483 pSgBuf->aSegs[0].pvSeg = RTMemAlloc(pSgBuf->aSegs[0].cbSeg);
484 if (!pSgBuf->pvUser || !pSgBuf->aSegs[0].pvSeg)
485 {
486 RTMemFree(pSgBuf->aSegs[0].pvSeg);
487 RTMemFree(pSgBuf->pvUser);
488 RTMemFree(pSgBuf);
489 /** @todo Implement the VERR_TRY_AGAIN semantics. */
490 return VERR_NO_MEMORY;
491 }
492 }
493
494 /*
495 * Initialize the S/G buffer and return.
496 */
497 pSgBuf->fFlags = PDMSCATTERGATHER_FLAGS_MAGIC | PDMSCATTERGATHER_FLAGS_OWNER_1;
498 pSgBuf->cbUsed = 0;
499 pSgBuf->cbAvailable = pSgBuf->aSegs[0].cbSeg;
500 pSgBuf->cSegs = 1;
501
502#if 0 /* poison */
503 memset(pSgBuf->aSegs[0].pvSeg, 'F', pSgBuf->aSegs[0].cbSeg);
504#endif
505 *ppSgBuf = pSgBuf;
506 return VINF_SUCCESS;
507}
508
509/**
510 * @interface_method_impl{PDMINETWORKUP,pfnFreeBuf}
511 */
512static DECLCALLBACK(int) drvNATNetworkUp_FreeBuf(PPDMINETWORKUP pInterface, PPDMSCATTERGATHER pSgBuf)
513{
514 PDRVNAT pThis = RT_FROM_MEMBER(pInterface, DRVNAT, INetworkUp);
515 Assert(RTCritSectIsOwner(&pThis->XmitLock));
516 drvNATFreeSgBuf(pThis, pSgBuf);
517 return VINF_SUCCESS;
518}
519
520/**
521 * @interface_method_impl{PDMINETWORKUP,pfnSendBuf}
522 */
523static DECLCALLBACK(int) drvNATNetworkUp_SendBuf(PPDMINETWORKUP pInterface, PPDMSCATTERGATHER pSgBuf, bool fOnWorkerThread)
524{
525 PDRVNAT pThis = RT_FROM_MEMBER(pInterface, DRVNAT, INetworkUp);
526 Assert((pSgBuf->fFlags & PDMSCATTERGATHER_FLAGS_OWNER_MASK) == PDMSCATTERGATHER_FLAGS_OWNER_1);
527 Assert(RTCritSectIsOwner(&pThis->XmitLock));
528
529 int rc;
530 if (pThis->pSlirpThread->enmState == PDMTHREADSTATE_RUNNING)
531 {
532 /* Set an FTM checkpoint as this operation changes the state permanently. */
533 PDMDrvHlpFTSetCheckpoint(pThis->pDrvIns, FTMCHECKPOINTTYPE_NETWORK);
534
535#ifdef VBOX_WITH_SLIRP_MT
536 PRTREQQUEUE pQueue = (PRTREQQUEUE)slirp_get_queue(pThis->pNATState);
537#else
538 PRTREQQUEUE pQueue = pThis->pSlirpReqQueue;
539#endif
540 rc = RTReqCallEx(pQueue, NULL /*ppReq*/, 0 /*cMillies*/, RTREQFLAGS_VOID | RTREQFLAGS_NO_WAIT,
541 (PFNRT)drvNATSendWorker, 2, pThis, pSgBuf);
542 if (RT_SUCCESS(rc))
543 {
544 drvNATNotifyNATThread(pThis, "drvNATNetworkUp_SendBuf");
545 return VINF_SUCCESS;
546 }
547
548 rc = VERR_NET_NO_BUFFER_SPACE;
549 }
550 else
551 rc = VERR_NET_DOWN;
552 drvNATFreeSgBuf(pThis, pSgBuf);
553 return rc;
554}
555
556/**
557 * @interface_method_impl{PDMINETWORKUP,pfnEndXmit}
558 */
559static DECLCALLBACK(void) drvNATNetworkUp_EndXmit(PPDMINETWORKUP pInterface)
560{
561 PDRVNAT pThis = RT_FROM_MEMBER(pInterface, DRVNAT, INetworkUp);
562 RTCritSectLeave(&pThis->XmitLock);
563}
564
565/**
566 * Get the NAT thread out of poll/WSAWaitForMultipleEvents
567 */
568static void drvNATNotifyNATThread(PDRVNAT pThis, const char *pszWho)
569{
570 int rc;
571#ifndef RT_OS_WINDOWS
572 /* kick poll() */
573 rc = RTFileWrite(pThis->PipeWrite, "", 1, NULL);
574#else
575 /* kick WSAWaitForMultipleEvents */
576 rc = WSASetEvent(pThis->hWakeupEvent);
577#endif
578 AssertRC(rc);
579}
580
581/**
582 * @interface_method_impl{PDMINETWORKUP,pfnSetPromiscuousMode}
583 */
584static DECLCALLBACK(void) drvNATNetworkUp_SetPromiscuousMode(PPDMINETWORKUP pInterface, bool fPromiscuous)
585{
586 LogFlow(("drvNATNetworkUp_SetPromiscuousMode: fPromiscuous=%d\n", fPromiscuous));
587 /* nothing to do */
588}
589
590/**
591 * Worker function for drvNATNetworkUp_NotifyLinkChanged().
592 * @thread "NAT" thread.
593 */
594static void drvNATNotifyLinkChangedWorker(PDRVNAT pThis, PDMNETWORKLINKSTATE enmLinkState)
595{
596 pThis->enmLinkState = pThis->enmLinkStateWant = enmLinkState;
597 switch (enmLinkState)
598 {
599 case PDMNETWORKLINKSTATE_UP:
600 LogRel(("NAT: link up\n"));
601 slirp_link_up(pThis->pNATState);
602 break;
603
604 case PDMNETWORKLINKSTATE_DOWN:
605 case PDMNETWORKLINKSTATE_DOWN_RESUME:
606 LogRel(("NAT: link down\n"));
607 slirp_link_down(pThis->pNATState);
608 break;
609
610 default:
611 AssertMsgFailed(("drvNATNetworkUp_NotifyLinkChanged: unexpected link state %d\n", enmLinkState));
612 }
613}
614
615/**
616 * Notification on link status changes.
617 *
618 * @param pInterface Pointer to the interface structure containing the called function pointer.
619 * @param enmLinkState The new link state.
620 * @thread EMT
621 */
622static DECLCALLBACK(void) drvNATNetworkUp_NotifyLinkChanged(PPDMINETWORKUP pInterface, PDMNETWORKLINKSTATE enmLinkState)
623{
624 PDRVNAT pThis = RT_FROM_MEMBER(pInterface, DRVNAT, INetworkUp);
625
626 LogFlow(("drvNATNetworkUp_NotifyLinkChanged: enmLinkState=%d\n", enmLinkState));
627
628 /* Don't queue new requests when the NAT thread is about to stop.
629 * But the VM could also be paused. So memorize the desired state. */
630 if (pThis->pSlirpThread->enmState != PDMTHREADSTATE_RUNNING)
631 {
632 pThis->enmLinkStateWant = enmLinkState;
633 return;
634 }
635
636 PRTREQ pReq;
637 int rc = RTReqCallEx(pThis->pSlirpReqQueue, &pReq, 0 /*cMillies*/, RTREQFLAGS_VOID,
638 (PFNRT)drvNATNotifyLinkChangedWorker, 2, pThis, enmLinkState);
639 if (RT_LIKELY(rc == VERR_TIMEOUT))
640 {
641 drvNATNotifyNATThread(pThis, "drvNATNetworkUp_NotifyLinkChanged");
642 rc = RTReqWait(pReq, RT_INDEFINITE_WAIT);
643 AssertRC(rc);
644 }
645 else
646 AssertRC(rc);
647 RTReqFree(pReq);
648}
649
650static void drvNATNotifyApplyPortForwardCommand(PDRVNAT pThis, bool fRemove,
651 bool fUdp, const char *pHostIp,
652 uint16_t u16HostPort, const char *pGuestIp, uint16_t u16GuestPort)
653{
654 RTMAC Mac;
655 RT_ZERO(Mac); /* can't get MAC here */
656 if (pThis->pIAboveConfig)
657 pThis->pIAboveConfig->pfnGetMac(pThis->pIAboveConfig, &Mac);
658
659 struct in_addr guestIp, hostIp;
660
661 if ( pHostIp == NULL
662 || inet_aton(pHostIp, &hostIp) == 0)
663 hostIp.s_addr = INADDR_ANY;
664
665 if ( pGuestIp == NULL
666 || inet_aton(pGuestIp, &guestIp) == 0)
667 guestIp.s_addr = pThis->GuestIP;
668
669 if (fRemove)
670 slirp_remove_redirect(pThis->pNATState, fUdp, hostIp, u16HostPort, guestIp, u16GuestPort);
671 else
672 slirp_add_redirect(pThis->pNATState, fUdp, hostIp, u16HostPort, guestIp, u16GuestPort, Mac.au8);
673}
674
675DECLCALLBACK(int) drvNATNetworkNatConfig_RedirectRuleCommand(PPDMINETWORKNATCONFIG pInterface, bool fRemove,
676 bool fUdp, const char *pHostIp,
677 uint16_t u16HostPort, const char *pGuestIp, uint16_t u16GuestPort)
678{
679 LogFlowFunc(("fRemove=%d, fUdp=%d, pHostIp=%s, u16HostPort=%u, pGuestIp=%s, u16GuestPort=%u\n",
680 RT_BOOL(fRemove), RT_BOOL(fUdp), pHostIp, u16HostPort, pGuestIp,
681 u16GuestPort));
682 PDRVNAT pThis = RT_FROM_MEMBER(pInterface, DRVNAT, INetworkNATCfg);
683 PRTREQ pReq;
684 int rc = RTReqCallEx(pThis->pSlirpReqQueue, &pReq, 0 /*cMillies*/, RTREQFLAGS_VOID,
685 (PFNRT)drvNATNotifyApplyPortForwardCommand, 7, pThis, fRemove,
686 fUdp, pHostIp, u16HostPort, pGuestIp, u16GuestPort);
687 if (RT_LIKELY(rc == VERR_TIMEOUT))
688 {
689 drvNATNotifyNATThread(pThis, "drvNATNetworkNatConfig_RedirectRuleCommand");
690 rc = RTReqWait(pReq, RT_INDEFINITE_WAIT);
691 AssertRC(rc);
692 }
693 else
694 AssertRC(rc);
695
696 RTReqFree(pReq);
697 port_forwarding_done:
698 return rc;
699}
700
701/**
702 * NAT thread handling the slirp stuff.
703 *
704 * The slirp implementation is single-threaded so we execute this enginre in a
705 * dedicated thread. We take care that this thread does not become the
706 * bottleneck: If the guest wants to send, a request is enqueued into the
707 * pSlirpReqQueue and handled asynchronously by this thread. If this thread
708 * wants to deliver packets to the guest, it enqueues a request into
709 * pRecvReqQueue which is later handled by the Recv thread.
710 */
711static DECLCALLBACK(int) drvNATAsyncIoThread(PPDMDRVINS pDrvIns, PPDMTHREAD pThread)
712{
713 PDRVNAT pThis = PDMINS_2_DATA(pDrvIns, PDRVNAT);
714 int nFDs = -1;
715#ifdef RT_OS_WINDOWS
716 HANDLE *phEvents = slirp_get_events(pThis->pNATState);
717 unsigned int cBreak = 0;
718#else /* RT_OS_WINDOWS */
719 unsigned int cPollNegRet = 0;
720#endif /* !RT_OS_WINDOWS */
721
722 LogFlow(("drvNATAsyncIoThread: pThis=%p\n", pThis));
723
724 if (pThread->enmState == PDMTHREADSTATE_INITIALIZING)
725 return VINF_SUCCESS;
726
727 if (pThis->enmLinkStateWant != pThis->enmLinkState)
728 drvNATNotifyLinkChangedWorker(pThis, pThis->enmLinkStateWant);
729
730 /*
731 * Polling loop.
732 */
733 while (pThread->enmState == PDMTHREADSTATE_RUNNING)
734 {
735 /*
736 * To prevent concurrent execution of sending/receiving threads
737 */
738#ifndef RT_OS_WINDOWS
739 nFDs = slirp_get_nsock(pThis->pNATState);
740 /* allocation for all sockets + Management pipe */
741 struct pollfd *polls = (struct pollfd *)RTMemAlloc((1 + nFDs) * sizeof(struct pollfd) + sizeof(uint32_t));
742 if (polls == NULL)
743 return VERR_NO_MEMORY;
744
745 /* don't pass the management pipe */
746 slirp_select_fill(pThis->pNATState, &nFDs, &polls[1]);
747
748 polls[0].fd = pThis->PipeRead;
749 /* POLLRDBAND usually doesn't used on Linux but seems used on Solaris */
750 polls[0].events = POLLRDNORM|POLLPRI|POLLRDBAND;
751 polls[0].revents = 0;
752
753 int cChangedFDs = poll(polls, nFDs + 1, slirp_get_timeout_ms(pThis->pNATState));
754 if (cChangedFDs < 0)
755 {
756 if (errno == EINTR)
757 {
758 Log2(("NAT: signal was caught while sleep on poll\n"));
759 /* No error, just process all outstanding requests but don't wait */
760 cChangedFDs = 0;
761 }
762 else if (cPollNegRet++ > 128)
763 {
764 LogRel(("NAT:Poll returns (%s) suppressed %d\n", strerror(errno), cPollNegRet));
765 cPollNegRet = 0;
766 }
767 }
768
769 if (cChangedFDs >= 0)
770 {
771 slirp_select_poll(pThis->pNATState, &polls[1], nFDs);
772 if (polls[0].revents & (POLLRDNORM|POLLPRI|POLLRDBAND))
773 {
774 /* drain the pipe */
775 char ch[1];
776 size_t cbRead;
777 int counter = 0;
778 /*
779 * drvNATSend decoupled so we don't know how many times
780 * device's thread sends before we've entered multiplex,
781 * so to avoid false alarm drain pipe here to the very end
782 *
783 * @todo: Probably we should counter drvNATSend to count how
784 * deep pipe has been filed before drain.
785 *
786 * XXX:Make it reading exactly we need to drain the pipe.
787 */
788 /** @todo use RTPipeCreate + RTPipeRead(,biggerbuffer) here, it's
789 * non-blocking. */
790 RTFileRead(pThis->PipeRead, &ch, 1, &cbRead);
791 }
792 }
793 /* process _all_ outstanding requests but don't wait */
794 RTReqProcess(pThis->pSlirpReqQueue, 0);
795 RTMemFree(polls);
796
797#else /* RT_OS_WINDOWS */
798 nFDs = -1;
799 slirp_select_fill(pThis->pNATState, &nFDs);
800 DWORD dwEvent = WSAWaitForMultipleEvents(nFDs, phEvents, FALSE,
801 slirp_get_timeout_ms(pThis->pNATState),
802 FALSE);
803 if ( (dwEvent < WSA_WAIT_EVENT_0 || dwEvent > WSA_WAIT_EVENT_0 + nFDs - 1)
804 && dwEvent != WSA_WAIT_TIMEOUT)
805 {
806 int error = WSAGetLastError();
807 LogRel(("NAT: WSAWaitForMultipleEvents returned %d (error %d)\n", dwEvent, error));
808 RTAssertPanic();
809 }
810
811 if (dwEvent == WSA_WAIT_TIMEOUT)
812 {
813 /* only check for slow/fast timers */
814 slirp_select_poll(pThis->pNATState, /* fTimeout=*/true, /*fIcmp=*/false);
815 continue;
816 }
817 /* poll the sockets in any case */
818 Log2(("%s: poll\n", __FUNCTION__));
819 slirp_select_poll(pThis->pNATState, /* fTimeout=*/false, /* fIcmp=*/(dwEvent == WSA_WAIT_EVENT_0));
820 /* process _all_ outstanding requests but don't wait */
821 RTReqProcess(pThis->pSlirpReqQueue, 0);
822# ifdef VBOX_NAT_DELAY_HACK
823 if (cBreak++ > 128)
824 {
825 cBreak = 0;
826 RTThreadSleep(2);
827 }
828# endif
829#endif /* RT_OS_WINDOWS */
830 }
831
832 return VINF_SUCCESS;
833}
834
835
836/**
837 * Unblock the send thread so it can respond to a state change.
838 *
839 * @returns VBox status code.
840 * @param pDevIns The pcnet device instance.
841 * @param pThread The send thread.
842 */
843static DECLCALLBACK(int) drvNATAsyncIoWakeup(PPDMDRVINS pDrvIns, PPDMTHREAD pThread)
844{
845 PDRVNAT pThis = PDMINS_2_DATA(pDrvIns, PDRVNAT);
846
847 drvNATNotifyNATThread(pThis, "drvNATAsyncIoWakeup");
848 return VINF_SUCCESS;
849}
850
851#ifdef VBOX_WITH_SLIRP_MT
852
853static DECLCALLBACK(int) drvNATAsyncIoGuest(PPDMDRVINS pDrvIns, PPDMTHREAD pThread)
854{
855 PDRVNAT pThis = PDMINS_2_DATA(pDrvIns, PDRVNAT);
856
857 if (pThread->enmState == PDMTHREADSTATE_INITIALIZING)
858 return VINF_SUCCESS;
859
860 while (pThread->enmState == PDMTHREADSTATE_RUNNING)
861 slirp_process_queue(pThis->pNATState);
862
863 return VINF_SUCCESS;
864}
865
866
867static DECLCALLBACK(int) drvNATAsyncIoGuestWakeup(PPDMDRVINS pDrvIns, PPDMTHREAD pThread)
868{
869 PDRVNAT pThis = PDMINS_2_DATA(pDrvIns, PDRVNAT);
870
871 return VINF_SUCCESS;
872}
873
874#endif /* VBOX_WITH_SLIRP_MT */
875
876/**
877 * Function called by slirp to check if it's possible to feed incoming data to the network port.
878 * @returns 1 if possible.
879 * @returns 0 if not possible.
880 */
881int slirp_can_output(void *pvUser)
882{
883 return 1;
884}
885
886void slirp_push_recv_thread(void *pvUser)
887{
888 PDRVNAT pThis = (PDRVNAT)pvUser;
889 Assert(pThis);
890 drvNATUrgRecvWakeup(pThis->pDrvIns, pThis->pUrgRecvThread);
891}
892
893void slirp_urg_output(void *pvUser, struct mbuf *m, const uint8_t *pu8Buf, int cb)
894{
895 PDRVNAT pThis = (PDRVNAT)pvUser;
896 Assert(pThis);
897
898 PRTREQ pReq = NULL;
899
900 /* don't queue new requests when the NAT thread is about to stop */
901 if (pThis->pSlirpThread->enmState != PDMTHREADSTATE_RUNNING)
902 return;
903
904 ASMAtomicIncU32(&pThis->cUrgPkts);
905 int rc = RTReqCallEx(pThis->pUrgRecvReqQueue, NULL /*ppReq*/, 0 /*cMillies*/, RTREQFLAGS_VOID | RTREQFLAGS_NO_WAIT,
906 (PFNRT)drvNATUrgRecvWorker, 4, pThis, pu8Buf, cb, m);
907 AssertRC(rc);
908 drvNATUrgRecvWakeup(pThis->pDrvIns, pThis->pUrgRecvThread);
909}
910
911/**
912 * Function called by slirp to feed incoming data to the NIC.
913 */
914void slirp_output(void *pvUser, struct mbuf *m, const uint8_t *pu8Buf, int cb)
915{
916 PDRVNAT pThis = (PDRVNAT)pvUser;
917 Assert(pThis);
918
919 LogFlow(("slirp_output BEGIN %x %d\n", pu8Buf, cb));
920 Log2(("slirp_output: pu8Buf=%p cb=%#x (pThis=%p)\n%.*Rhxd\n", pu8Buf, cb, pThis, cb, pu8Buf));
921
922 PRTREQ pReq = NULL;
923
924 /* don't queue new requests when the NAT thread is about to stop */
925 if (pThis->pSlirpThread->enmState != PDMTHREADSTATE_RUNNING)
926 return;
927
928 ASMAtomicIncU32(&pThis->cPkts);
929 int rc = RTReqCallEx(pThis->pRecvReqQueue, NULL /*ppReq*/, 0 /*cMillies*/, RTREQFLAGS_VOID | RTREQFLAGS_NO_WAIT,
930 (PFNRT)drvNATRecvWorker, 4, pThis, pu8Buf, cb, m);
931 AssertRC(rc);
932 drvNATRecvWakeup(pThis->pDrvIns, pThis->pRecvThread);
933 STAM_COUNTER_INC(&pThis->StatQueuePktSent);
934}
935
936
937/**
938 * @interface_method_impl{PDMIBASE,pfnQueryInterface}
939 */
940static DECLCALLBACK(void *) drvNATQueryInterface(PPDMIBASE pInterface, const char *pszIID)
941{
942 PPDMDRVINS pDrvIns = PDMIBASE_2_PDMDRV(pInterface);
943 PDRVNAT pThis = PDMINS_2_DATA(pDrvIns, PDRVNAT);
944
945 PDMIBASE_RETURN_INTERFACE(pszIID, PDMIBASE, &pDrvIns->IBase);
946 PDMIBASE_RETURN_INTERFACE(pszIID, PDMINETWORKUP, &pThis->INetworkUp);
947 PDMIBASE_RETURN_INTERFACE(pszIID, PDMINETWORKNATCONFIG, &pThis->INetworkNATCfg);
948 return NULL;
949}
950
951
952/**
953 * Get the MAC address into the slirp stack.
954 *
955 * Called by drvNATLoadDone and drvNATPowerOn.
956 */
957static void drvNATSetMac(PDRVNAT pThis)
958{
959 if (pThis->pIAboveConfig)
960 {
961 RTMAC Mac;
962 pThis->pIAboveConfig->pfnGetMac(pThis->pIAboveConfig, &Mac);
963 /* Re-activate the port forwarding. If */
964 slirp_set_ethaddr_and_activate_port_forwarding(pThis->pNATState, Mac.au8, pThis->GuestIP);
965 }
966}
967
968
969/**
970 * After loading we have to pass the MAC address of the ethernet device to the slirp stack.
971 * Otherwise the guest is not reachable until it performs a DHCP request or an ARP request
972 * (usually done during guest boot).
973 */
974static DECLCALLBACK(int) drvNATLoadDone(PPDMDRVINS pDrvIns, PSSMHANDLE pSSMHandle)
975{
976 PDRVNAT pThis = PDMINS_2_DATA(pDrvIns, PDRVNAT);
977 drvNATSetMac(pThis);
978 return VINF_SUCCESS;
979}
980
981
982/**
983 * Some guests might not use DHCP to retrieve an IP but use a static IP.
984 */
985static DECLCALLBACK(void) drvNATPowerOn(PPDMDRVINS pDrvIns)
986{
987 PDRVNAT pThis = PDMINS_2_DATA(pDrvIns, PDRVNAT);
988 drvNATSetMac(pThis);
989}
990
991
992/**
993 * Info handler.
994 */
995static DECLCALLBACK(void) drvNATInfo(PPDMDRVINS pDrvIns, PCDBGFINFOHLP pHlp, const char *pszArgs)
996{
997 PDRVNAT pThis = PDMINS_2_DATA(pDrvIns, PDRVNAT);
998 slirp_info(pThis->pNATState, pHlp, pszArgs);
999}
1000
1001
1002/**
1003 * Sets up the redirectors.
1004 *
1005 * @returns VBox status code.
1006 * @param pCfg The configuration handle.
1007 */
1008static int drvNATConstructRedir(unsigned iInstance, PDRVNAT pThis, PCFGMNODE pCfg, RTIPV4ADDR Network)
1009{
1010 RTMAC Mac;
1011 RT_ZERO(Mac); /* can't get MAC here */
1012
1013 /*
1014 * Enumerate redirections.
1015 */
1016 for (PCFGMNODE pNode = CFGMR3GetFirstChild(pCfg); pNode; pNode = CFGMR3GetNextChild(pNode))
1017 {
1018 /*
1019 * Validate the port forwarding config.
1020 */
1021 if (!CFGMR3AreValuesValid(pNode, "Protocol\0UDP\0HostPort\0GuestPort\0GuestIP\0BindIP\0"))
1022 return PDMDRV_SET_ERROR(pThis->pDrvIns, VERR_PDM_DRVINS_UNKNOWN_CFG_VALUES, N_("Unknown configuration in port forwarding"));
1023
1024 /* protocol type */
1025 bool fUDP;
1026 char szProtocol[32];
1027 int rc;
1028 GET_STRING(rc, pThis, pNode, "Protocol", szProtocol[0], sizeof(szProtocol));
1029 if (rc == VERR_CFGM_VALUE_NOT_FOUND)
1030 {
1031 fUDP = false;
1032 GET_BOOL(rc, pThis, pNode, "UDP", fUDP);
1033 }
1034 else if (RT_SUCCESS(rc))
1035 {
1036 if (!RTStrICmp(szProtocol, "TCP"))
1037 fUDP = false;
1038 else if (!RTStrICmp(szProtocol, "UDP"))
1039 fUDP = true;
1040 else
1041 return PDMDrvHlpVMSetError(pThis->pDrvIns, VERR_INVALID_PARAMETER, RT_SRC_POS,
1042 N_("NAT#%d: Invalid configuration value for \"Protocol\": \"%s\""),
1043 iInstance, szProtocol);
1044 }
1045 /* host port */
1046 int32_t iHostPort;
1047 GET_S32_STRICT(rc, pThis, pNode, "HostPort", iHostPort);
1048
1049 /* guest port */
1050 int32_t iGuestPort;
1051 GET_S32_STRICT(rc, pThis, pNode, "GuestPort", iGuestPort);
1052
1053 /* guest address */
1054 struct in_addr GuestIP;
1055 /* @todo (vvl) use CTL_* */
1056 GETIP_DEF(rc, pThis, pNode, GuestIP, htonl(Network | CTL_GUEST));
1057
1058 /* Store the guest IP for re-establishing the port-forwarding rules. Note that GuestIP
1059 * is not documented. Without */
1060 if (pThis->GuestIP == INADDR_ANY)
1061 pThis->GuestIP = GuestIP.s_addr;
1062
1063 /*
1064 * Call slirp about it.
1065 */
1066 struct in_addr BindIP;
1067 GETIP_DEF(rc, pThis, pNode, BindIP, INADDR_ANY);
1068 if (slirp_add_redirect(pThis->pNATState, fUDP, BindIP, iHostPort, GuestIP, iGuestPort, Mac.au8) < 0)
1069 return PDMDrvHlpVMSetError(pThis->pDrvIns, VERR_NAT_REDIR_SETUP, RT_SRC_POS,
1070 N_("NAT#%d: configuration error: failed to set up "
1071 "redirection of %d to %d. Probably a conflict with "
1072 "existing services or other rules"), iInstance, iHostPort,
1073 iGuestPort);
1074 } /* for each redir rule */
1075
1076 return VINF_SUCCESS;
1077}
1078
1079
1080/**
1081 * Destruct a driver instance.
1082 *
1083 * Most VM resources are freed by the VM. This callback is provided so that any non-VM
1084 * resources can be freed correctly.
1085 *
1086 * @param pDrvIns The driver instance data.
1087 */
1088static DECLCALLBACK(void) drvNATDestruct(PPDMDRVINS pDrvIns)
1089{
1090 PDRVNAT pThis = PDMINS_2_DATA(pDrvIns, PDRVNAT);
1091 LogFlow(("drvNATDestruct:\n"));
1092 PDMDRV_CHECK_VERSIONS_RETURN_VOID(pDrvIns);
1093
1094 if (pThis->pNATState)
1095 {
1096 slirp_term(pThis->pNATState);
1097 slirp_deregister_statistics(pThis->pNATState, pDrvIns);
1098#ifdef VBOX_WITH_STATISTICS
1099# define DRV_PROFILE_COUNTER(name, dsc) DEREGISTER_COUNTER(name, pThis)
1100# define DRV_COUNTING_COUNTER(name, dsc) DEREGISTER_COUNTER(name, pThis)
1101# include "counters.h"
1102#endif
1103 pThis->pNATState = NULL;
1104 }
1105
1106 RTReqDestroyQueue(pThis->pSlirpReqQueue);
1107 pThis->pSlirpReqQueue = NULL;
1108
1109 RTReqDestroyQueue(pThis->pUrgRecvReqQueue);
1110 pThis->pUrgRecvReqQueue = NULL;
1111
1112 RTSemEventDestroy(pThis->EventRecv);
1113 pThis->EventRecv = NIL_RTSEMEVENT;
1114
1115 RTSemEventDestroy(pThis->EventUrgRecv);
1116 pThis->EventUrgRecv = NIL_RTSEMEVENT;
1117
1118 if (RTCritSectIsInitialized(&pThis->DevAccessLock))
1119 RTCritSectDelete(&pThis->DevAccessLock);
1120
1121 if (RTCritSectIsInitialized(&pThis->XmitLock))
1122 RTCritSectDelete(&pThis->XmitLock);
1123}
1124
1125
1126/**
1127 * Construct a NAT network transport driver instance.
1128 *
1129 * @copydoc FNPDMDRVCONSTRUCT
1130 */
1131static DECLCALLBACK(int) drvNATConstruct(PPDMDRVINS pDrvIns, PCFGMNODE pCfg, uint32_t fFlags)
1132{
1133 PDRVNAT pThis = PDMINS_2_DATA(pDrvIns, PDRVNAT);
1134 LogFlow(("drvNATConstruct:\n"));
1135 PDMDRV_CHECK_VERSIONS_RETURN(pDrvIns);
1136
1137 /*
1138 * Validate the config.
1139 */
1140 if (!CFGMR3AreValuesValid(pCfg,
1141 "PassDomain\0TFTPPrefix\0BootFile\0Network"
1142 "\0NextServer\0DNSProxy\0BindIP\0UseHostResolver\0"
1143 "SlirpMTU\0AliasMode\0"
1144 "SockRcv\0SockSnd\0TcpRcv\0TcpSnd\0"))
1145 return PDMDRV_SET_ERROR(pDrvIns, VERR_PDM_DRVINS_UNKNOWN_CFG_VALUES,
1146 N_("Unknown NAT configuration option, only supports PassDomain,"
1147 " TFTPPrefix, BootFile and Network"));
1148
1149 /*
1150 * Init the static parts.
1151 */
1152 pThis->pDrvIns = pDrvIns;
1153 pThis->pNATState = NULL;
1154 pThis->pszTFTPPrefix = NULL;
1155 pThis->pszBootFile = NULL;
1156 pThis->pszNextServer = NULL;
1157 pThis->pSlirpReqQueue = NULL;
1158 pThis->pUrgRecvReqQueue = NULL;
1159 pThis->EventRecv = NIL_RTSEMEVENT;
1160 pThis->EventUrgRecv = NIL_RTSEMEVENT;
1161
1162 /* IBase */
1163 pDrvIns->IBase.pfnQueryInterface = drvNATQueryInterface;
1164
1165 /* INetwork */
1166 pThis->INetworkUp.pfnBeginXmit = drvNATNetworkUp_BeginXmit;
1167 pThis->INetworkUp.pfnAllocBuf = drvNATNetworkUp_AllocBuf;
1168 pThis->INetworkUp.pfnFreeBuf = drvNATNetworkUp_FreeBuf;
1169 pThis->INetworkUp.pfnSendBuf = drvNATNetworkUp_SendBuf;
1170 pThis->INetworkUp.pfnEndXmit = drvNATNetworkUp_EndXmit;
1171 pThis->INetworkUp.pfnSetPromiscuousMode = drvNATNetworkUp_SetPromiscuousMode;
1172 pThis->INetworkUp.pfnNotifyLinkChanged = drvNATNetworkUp_NotifyLinkChanged;
1173
1174 /* NAT engine configuration */
1175 pThis->INetworkNATCfg.pfnRedirectRuleCommand = drvNATNetworkNatConfig_RedirectRuleCommand;
1176
1177 /*
1178 * Get the configuration settings.
1179 */
1180 int rc;
1181 bool fPassDomain = true;
1182 GET_BOOL(rc, pThis, pCfg, "PassDomain", fPassDomain);
1183
1184 GET_STRING_ALLOC(rc, pThis, pCfg, "TFTPPrefix", pThis->pszTFTPPrefix);
1185 GET_STRING_ALLOC(rc, pThis, pCfg, "BootFile", pThis->pszBootFile);
1186 GET_STRING_ALLOC(rc, pThis, pCfg, "NextServer", pThis->pszNextServer);
1187
1188 int fDNSProxy = 0;
1189 GET_S32(rc, pThis, pCfg, "DNSProxy", fDNSProxy);
1190 int fUseHostResolver = 0;
1191 GET_S32(rc, pThis, pCfg, "UseHostResolver", fUseHostResolver);
1192 int MTU = 1500;
1193 GET_S32(rc, pThis, pCfg, "SlirpMTU", MTU);
1194 int i32AliasMode = 0;
1195 int i32MainAliasMode = 0;
1196 GET_S32(rc, pThis, pCfg, "AliasMode", i32MainAliasMode);
1197
1198 i32AliasMode |= (i32MainAliasMode & 0x1 ? 0x1 : 0);
1199 i32AliasMode |= (i32MainAliasMode & 0x2 ? 0x40 : 0);
1200 i32AliasMode |= (i32MainAliasMode & 0x4 ? 0x4 : 0);
1201 /*
1202 * Query the network port interface.
1203 */
1204 pThis->pIAboveNet = PDMIBASE_QUERY_INTERFACE(pDrvIns->pUpBase, PDMINETWORKDOWN);
1205 if (!pThis->pIAboveNet)
1206 return PDMDRV_SET_ERROR(pDrvIns, VERR_PDM_MISSING_INTERFACE_ABOVE,
1207 N_("Configuration error: the above device/driver didn't "
1208 "export the network port interface"));
1209 pThis->pIAboveConfig = PDMIBASE_QUERY_INTERFACE(pDrvIns->pUpBase, PDMINETWORKCONFIG);
1210 if (!pThis->pIAboveConfig)
1211 return PDMDRV_SET_ERROR(pDrvIns, VERR_PDM_MISSING_INTERFACE_ABOVE,
1212 N_("Configuration error: the above device/driver didn't "
1213 "export the network config interface"));
1214
1215 /* Generate a network address for this network card. */
1216 char szNetwork[32]; /* xxx.xxx.xxx.xxx/yy */
1217 GET_STRING(rc, pThis, pCfg, "Network", szNetwork[0], sizeof(szNetwork));
1218 if (rc == VERR_CFGM_VALUE_NOT_FOUND)
1219 return PDMDrvHlpVMSetError(pDrvIns, rc, RT_SRC_POS, N_("NAT%d: Configuration error: "
1220 "missing network"),
1221 pDrvIns->iInstance, szNetwork);
1222
1223 RTIPV4ADDR Network;
1224 RTIPV4ADDR Netmask;
1225 rc = RTCidrStrToIPv4(szNetwork, &Network, &Netmask);
1226 if (RT_FAILURE(rc))
1227 return PDMDrvHlpVMSetError(pDrvIns, rc, RT_SRC_POS, N_("NAT#%d: Configuration error: "
1228 "network '%s' describes not a valid IPv4 network"),
1229 pDrvIns->iInstance, szNetwork);
1230
1231 /*
1232 * Initialize slirp.
1233 */
1234 rc = slirp_init(&pThis->pNATState, RT_H2N_U32(Network), Netmask,
1235 fPassDomain, !!fUseHostResolver, i32AliasMode, pThis);
1236 if (RT_SUCCESS(rc))
1237 {
1238 slirp_set_dhcp_TFTP_prefix(pThis->pNATState, pThis->pszTFTPPrefix);
1239 slirp_set_dhcp_TFTP_bootfile(pThis->pNATState, pThis->pszBootFile);
1240 slirp_set_dhcp_next_server(pThis->pNATState, pThis->pszNextServer);
1241 slirp_set_dhcp_dns_proxy(pThis->pNATState, !!fDNSProxy);
1242 slirp_set_mtu(pThis->pNATState, MTU);
1243 char *pszBindIP = NULL;
1244 GET_STRING_ALLOC(rc, pThis, pCfg, "BindIP", pszBindIP);
1245 rc = slirp_set_binding_address(pThis->pNATState, pszBindIP);
1246 if (rc != 0)
1247 LogRel(("NAT: value of BindIP has been ignored\n"));
1248
1249 if(pszBindIP != NULL)
1250 MMR3HeapFree(pszBindIP);
1251#define SLIRP_SET_TUNING_VALUE(name, setter) \
1252 do \
1253 { \
1254 int len = 0; \
1255 rc = CFGMR3QueryS32(pCfg, name, &len); \
1256 if (RT_SUCCESS(rc)) \
1257 setter(pThis->pNATState, len); \
1258 } while(0)
1259
1260 SLIRP_SET_TUNING_VALUE("SockRcv", slirp_set_rcvbuf);
1261 SLIRP_SET_TUNING_VALUE("SockSnd", slirp_set_sndbuf);
1262 SLIRP_SET_TUNING_VALUE("TcpRcv", slirp_set_tcp_rcvspace);
1263 SLIRP_SET_TUNING_VALUE("TcpSnd", slirp_set_tcp_sndspace);
1264
1265 slirp_register_statistics(pThis->pNATState, pDrvIns);
1266#ifdef VBOX_WITH_STATISTICS
1267# define DRV_PROFILE_COUNTER(name, dsc) REGISTER_COUNTER(name, pThis, STAMTYPE_PROFILE, STAMUNIT_TICKS_PER_CALL, dsc)
1268# define DRV_COUNTING_COUNTER(name, dsc) REGISTER_COUNTER(name, pThis, STAMTYPE_COUNTER, STAMUNIT_COUNT, dsc)
1269# include "counters.h"
1270#endif
1271
1272 rc = drvNATConstructRedir(pDrvIns->iInstance, pThis, pCfg, Network);
1273 if (RT_SUCCESS(rc))
1274 {
1275 /*
1276 * Register a load done notification to get the MAC address into the slirp
1277 * engine after we loaded a guest state.
1278 */
1279 rc = PDMDrvHlpSSMRegisterLoadDone(pDrvIns, drvNATLoadDone);
1280 AssertRCReturn(rc, rc);
1281
1282 rc = RTReqCreateQueue(&pThis->pSlirpReqQueue);
1283 if (RT_FAILURE(rc))
1284 {
1285 LogRel(("NAT: Can't create request queue\n"));
1286 return rc;
1287 }
1288
1289 rc = RTReqCreateQueue(&pThis->pRecvReqQueue);
1290 if (RT_FAILURE(rc))
1291 {
1292 LogRel(("NAT: Can't create request queue\n"));
1293 return rc;
1294 }
1295
1296 rc = RTReqCreateQueue(&pThis->pUrgRecvReqQueue);
1297 if (RT_FAILURE(rc))
1298 {
1299 LogRel(("NAT: Can't create request queue\n"));
1300 return rc;
1301 }
1302
1303 rc = PDMDrvHlpThreadCreate(pDrvIns, &pThis->pRecvThread, pThis, drvNATRecv,
1304 drvNATRecvWakeup, 128 * _1K, RTTHREADTYPE_IO, "NATRX");
1305 AssertRCReturn(rc, rc);
1306
1307 rc = RTSemEventCreate(&pThis->EventRecv);
1308 AssertRCReturn(rc, rc);
1309
1310 rc = PDMDrvHlpThreadCreate(pDrvIns, &pThis->pUrgRecvThread, pThis, drvNATUrgRecv,
1311 drvNATUrgRecvWakeup, 128 * _1K, RTTHREADTYPE_IO, "NATURGRX");
1312 AssertRCReturn(rc, rc);
1313
1314 rc = RTSemEventCreate(&pThis->EventRecv);
1315 AssertRCReturn(rc, rc);
1316
1317 rc = RTSemEventCreate(&pThis->EventUrgRecv);
1318 AssertRCReturn(rc, rc);
1319
1320 rc = RTCritSectInit(&pThis->DevAccessLock);
1321 AssertRCReturn(rc, rc);
1322
1323 rc = RTCritSectInit(&pThis->XmitLock);
1324 AssertRCReturn(rc, rc);
1325
1326 char szTmp[128];
1327 RTStrPrintf(szTmp, sizeof(szTmp), "nat%d", pDrvIns->iInstance);
1328 PDMDrvHlpDBGFInfoRegister(pDrvIns, szTmp, "NAT info.", drvNATInfo);
1329
1330#ifndef RT_OS_WINDOWS
1331 /*
1332 * Create the control pipe.
1333 */
1334 int fds[2];
1335 if (pipe(&fds[0]) != 0) /** @todo RTPipeCreate() or something... */
1336 {
1337 rc = RTErrConvertFromErrno(errno);
1338 AssertRC(rc);
1339 return rc;
1340 }
1341 pThis->PipeRead = fds[0];
1342 pThis->PipeWrite = fds[1];
1343#else
1344 pThis->hWakeupEvent = CreateEvent(NULL, FALSE, FALSE, NULL); /* auto-reset event */
1345 slirp_register_external_event(pThis->pNATState, pThis->hWakeupEvent,
1346 VBOX_WAKEUP_EVENT_INDEX);
1347#endif
1348
1349 rc = PDMDrvHlpThreadCreate(pDrvIns, &pThis->pSlirpThread, pThis, drvNATAsyncIoThread,
1350 drvNATAsyncIoWakeup, 128 * _1K, RTTHREADTYPE_IO, "NAT");
1351 AssertRC(rc);
1352
1353#ifdef VBOX_WITH_SLIRP_MT
1354 rc = PDMDrvHlpThreadCreate(pDrvIns, &pThis->pGuestThread, pThis, drvNATAsyncIoGuest,
1355 drvNATAsyncIoGuestWakeup, 128 * _1K, RTTHREADTYPE_IO, "NATGUEST");
1356 AssertRC(rc);
1357#endif
1358
1359 pThis->enmLinkState = pThis->enmLinkStateWant = PDMNETWORKLINKSTATE_UP;
1360
1361 /* might return VINF_NAT_DNS */
1362 return rc;
1363 }
1364
1365 /* failure path */
1366 slirp_term(pThis->pNATState);
1367 pThis->pNATState = NULL;
1368 }
1369 else
1370 {
1371 PDMDRV_SET_ERROR(pDrvIns, rc, N_("Unknown error during NAT networking setup: "));
1372 AssertMsgFailed(("Add error message for rc=%d (%Rrc)\n", rc, rc));
1373 }
1374
1375 return rc;
1376}
1377
1378
1379/**
1380 * NAT network transport driver registration record.
1381 */
1382const PDMDRVREG g_DrvNAT =
1383{
1384 /* u32Version */
1385 PDM_DRVREG_VERSION,
1386 /* szName */
1387 "NAT",
1388 /* szRCMod */
1389 "",
1390 /* szR0Mod */
1391 "",
1392 /* pszDescription */
1393 "NAT Network Transport Driver",
1394 /* fFlags */
1395 PDM_DRVREG_FLAGS_HOST_BITS_DEFAULT,
1396 /* fClass. */
1397 PDM_DRVREG_CLASS_NETWORK,
1398 /* cMaxInstances */
1399 16,
1400 /* cbInstance */
1401 sizeof(DRVNAT),
1402 /* pfnConstruct */
1403 drvNATConstruct,
1404 /* pfnDestruct */
1405 drvNATDestruct,
1406 /* pfnRelocate */
1407 NULL,
1408 /* pfnIOCtl */
1409 NULL,
1410 /* pfnPowerOn */
1411 drvNATPowerOn,
1412 /* pfnReset */
1413 NULL,
1414 /* pfnSuspend */
1415 NULL,
1416 /* pfnResume */
1417 NULL,
1418 /* pfnAttach */
1419 NULL,
1420 /* pfnDetach */
1421 NULL,
1422 /* pfnPowerOff */
1423 NULL,
1424 /* pfnSoftReset */
1425 NULL,
1426 /* u32EndVersion */
1427 PDM_DRVREG_VERSION
1428};
1429
Note: See TracBrowser for help on using the repository browser.

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