VirtualBox

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

Last change on this file since 27411 was 26574, checked in by vboxsync, 15 years ago

Networking: Preparing to make the driver return a send buffer to the device emulation.

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