VirtualBox

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

Last change on this file since 15793 was 15788, checked in by vboxsync, 16 years ago

NAT: fixed return value of drvNATQueueConsumer() if pfnWaitReceiveAvail() returns an error

  • Property svn:eol-style set to native
  • Property svn:keywords set to Author Date Id Revision
File size: 29.4 KB
Line 
1/** @file
2 *
3 * VBox network devices:
4 * NAT network transport driver
5 */
6
7/*
8 * Copyright (C) 2006-2007 Sun Microsystems, Inc.
9 *
10 * This file is part of VirtualBox Open Source Edition (OSE), as
11 * available from http://www.virtualbox.org. This file is free software;
12 * you can redistribute it and/or modify it under the terms of the GNU
13 * General Public License (GPL) as published by the Free Software
14 * Foundation, in version 2 as it comes in the "COPYING" file of the
15 * VirtualBox OSE distribution. VirtualBox OSE is distributed in the
16 * hope that it will be useful, but WITHOUT ANY WARRANTY of any kind.
17 *
18 * Please contact Sun Microsystems, Inc., 4150 Network Circle, Santa
19 * Clara, CA 95054 USA or visit http://www.sun.com if you need
20 * additional information or have any questions.
21 */
22
23
24/*******************************************************************************
25* Header Files *
26*******************************************************************************/
27#define LOG_GROUP LOG_GROUP_DRV_NAT
28#define __STDC_LIMIT_MACROS
29#define __STDC_CONSTANT_MACROS
30#include "Network/slirp/libslirp.h"
31#include <VBox/pdmdrv.h>
32#include <iprt/assert.h>
33#include <iprt/file.h>
34#include <iprt/mem.h>
35#include <iprt/string.h>
36#include <iprt/critsect.h>
37#include <iprt/cidr.h>
38#include <iprt/stream.h>
39
40#include "Builtins.h"
41
42#ifdef VBOX_WITH_SIMPLIFIED_SLIRP_SYNC
43# ifndef RT_OS_WINDOWS
44# include <unistd.h>
45# endif
46# include <errno.h>
47# include <iprt/semaphore.h>
48# include <iprt/req.h>
49#endif
50
51
52/*******************************************************************************
53* Structures and Typedefs *
54*******************************************************************************/
55/**
56 * NAT network transport driver instance data.
57 */
58typedef struct DRVNAT
59{
60 /** The network interface. */
61 PDMINETWORKCONNECTOR INetworkConnector;
62 /** The port we're attached to. */
63 PPDMINETWORKPORT pPort;
64 /** The network config of the port we're attached to. */
65 PPDMINETWORKCONFIG pConfig;
66 /** Pointer to the driver instance. */
67 PPDMDRVINS pDrvIns;
68#ifndef VBOX_WITH_SIMPLIFIED_SLIRP_SYNC
69 /** Slirp critical section. */
70 RTCRITSECT CritSect;
71#endif
72 /** Link state */
73 PDMNETWORKLINKSTATE enmLinkState;
74 /** NAT state for this instance. */
75 PNATState pNATState;
76 /** TFTP directory prefix. */
77 char *pszTFTPPrefix;
78 /** Boot file name to provide in the DHCP server response. */
79 char *pszBootFile;
80#ifdef VBOX_WITH_SIMPLIFIED_SLIRP_SYNC
81 /* polling thread */
82 PPDMTHREAD pThread;
83 /** Queue for NAT-thread-external events. */
84 PRTREQQUEUE pReqQueue;
85 /* Send queue */
86 PPDMQUEUE pSendQueue;
87# ifndef RT_OS_WINDOWS
88 /** The write end of the control pipe. */
89 RTFILE PipeWrite;
90 /** The read end of the control pipe. */
91 RTFILE PipeRead;
92# else
93 /** for external notification */
94 HANDLE hWakeupEvent;
95# endif
96#endif
97} DRVNAT, *PDRVNAT;
98
99typedef struct DRVNATQUEUITEM
100{
101 /** The core part owned by the queue manager. */
102 PDMQUEUEITEMCORE Core;
103 /** The buffer for output to guest. */
104 const uint8_t *pu8Buf;
105 /* size of buffer */
106 size_t cb;
107} DRVNATQUEUITEM, *PDRVNATQUEUITEM;
108
109/** Converts a pointer to NAT::INetworkConnector to a PRDVNAT. */
110#define PDMINETWORKCONNECTOR_2_DRVNAT(pInterface) ( (PDRVNAT)((uintptr_t)pInterface - RT_OFFSETOF(DRVNAT, INetworkConnector)) )
111
112
113/**
114 * Worker function for drvNATSend().
115 * @thread "NAT" thread.
116 */
117static void drvNATSendWorker(PDRVNAT pThis, const void *pvBuf, size_t cb)
118{
119 Assert(pThis->enmLinkState == PDMNETWORKLINKSTATE_UP);
120 if (pThis->enmLinkState == PDMNETWORKLINKSTATE_UP)
121 slirp_input(pThis->pNATState, (uint8_t *)pvBuf, cb);
122}
123
124/**
125 * Send data to the network.
126 *
127 * @returns VBox status code.
128 * @param pInterface Pointer to the interface structure containing the called function pointer.
129 * @param pvBuf Data to send.
130 * @param cb Number of bytes to send.
131 * @thread EMT
132 */
133static DECLCALLBACK(int) drvNATSend(PPDMINETWORKCONNECTOR pInterface, const void *pvBuf, size_t cb)
134{
135 PDRVNAT pThis = PDMINETWORKCONNECTOR_2_DRVNAT(pInterface);
136
137 LogFlow(("drvNATSend: pvBuf=%p cb=%#x\n", pvBuf, cb));
138 Log2(("drvNATSend: pvBuf=%p cb=%#x\n%.*Rhxd\n", pvBuf, cb, cb, pvBuf));
139
140#ifdef VBOX_WITH_SIMPLIFIED_SLIRP_SYNC
141
142 PRTREQ pReq = NULL;
143 int rc;
144 /* don't queue new requests when the NAT thread is about to stop */
145 if (pThis->pThread->enmState != PDMTHREADSTATE_RUNNING)
146 return VINF_SUCCESS;
147 rc = RTReqAlloc(pThis->pReqQueue, &pReq, RTREQTYPE_INTERNAL);
148 AssertReleaseRC(rc);
149 pReq->u.Internal.pfn = (PFNRT)drvNATSendWorker;
150 pReq->u.Internal.cArgs = 3;
151 pReq->u.Internal.aArgs[0] = (uintptr_t)pThis;
152 pReq->u.Internal.aArgs[1] = (uintptr_t)pvBuf;
153 pReq->u.Internal.aArgs[2] = (uintptr_t)cb;
154 pReq->fFlags = RTREQFLAGS_VOID;
155 rc = RTReqQueue(pReq, 0); /* don't wait, we have to wakeup the NAT thread fist */
156 if (RT_LIKELY(rc == VERR_TIMEOUT))
157 {
158# ifndef RT_OS_WINDOWS
159 /* kick select() */
160 rc = RTFileWrite(pThis->PipeWrite, "", 1, NULL);
161 AssertRC(rc);
162# else
163 /* kick WSAWaitForMultipleEvents */
164 rc = WSASetEvent(pThis->hWakeupEvent);
165 AssertRelease(rc == TRUE);
166# endif
167 rc = RTReqWait(pReq, RT_INDEFINITE_WAIT);
168 AssertReleaseRC(rc);
169 }
170 else
171 AssertReleaseRC(rc);
172 RTReqFree(pReq);
173
174#else /* !VBOX_WITH_SIMPLIFIED_SLIRP_SYNC */
175
176 int rc = RTCritSectEnter(&pThis->CritSect);
177 AssertReleaseRC(rc);
178
179 drvNATSendWorker(pThis, pvBuf, cb);
180
181 RTCritSectLeave(&pThis->CritSect);
182
183#endif /* !VBOX_WITH_SIMPLIFIED_SLIRP_SYNC */
184
185 LogFlow(("drvNATSend: end\n"));
186 return VINF_SUCCESS;
187}
188
189
190/**
191 * Set promiscuous mode.
192 *
193 * This is called when the promiscuous mode is set. This means that there doesn't have
194 * to be a mode change when it's called.
195 *
196 * @param pInterface Pointer to the interface structure containing the called function pointer.
197 * @param fPromiscuous Set if the adaptor is now in promiscuous mode. Clear if it is not.
198 * @thread EMT
199 */
200static DECLCALLBACK(void) drvNATSetPromiscuousMode(PPDMINETWORKCONNECTOR pInterface, bool fPromiscuous)
201{
202 LogFlow(("drvNATSetPromiscuousMode: fPromiscuous=%d\n", fPromiscuous));
203 /* nothing to do */
204}
205
206/**
207 * Worker function for drvNATNotifyLinkChanged().
208 * @thread "NAT" thread.
209 */
210static void drvNATNotifyLinkChangedWorker(PDRVNAT pThis, PDMNETWORKLINKSTATE enmLinkState)
211{
212 pThis->enmLinkState = enmLinkState;
213
214 switch (enmLinkState)
215 {
216 case PDMNETWORKLINKSTATE_UP:
217 LogRel(("NAT: link up\n"));
218 slirp_link_up(pThis->pNATState);
219 break;
220
221 case PDMNETWORKLINKSTATE_DOWN:
222 case PDMNETWORKLINKSTATE_DOWN_RESUME:
223 LogRel(("NAT: link down\n"));
224 slirp_link_down(pThis->pNATState);
225 break;
226
227 default:
228 AssertMsgFailed(("drvNATNotifyLinkChanged: unexpected link state %d\n", enmLinkState));
229 }
230}
231
232/**
233 * Notification on link status changes.
234 *
235 * @param pInterface Pointer to the interface structure containing the called function pointer.
236 * @param enmLinkState The new link state.
237 * @thread EMT
238 */
239static DECLCALLBACK(void) drvNATNotifyLinkChanged(PPDMINETWORKCONNECTOR pInterface, PDMNETWORKLINKSTATE enmLinkState)
240{
241 PDRVNAT pThis = PDMINETWORKCONNECTOR_2_DRVNAT(pInterface);
242
243 LogFlow(("drvNATNotifyLinkChanged: enmLinkState=%d\n", enmLinkState));
244
245#ifdef VBOX_WITH_SIMPLIFIED_SLIRP_SYNC
246
247 PRTREQ pReq = NULL;
248 /* don't queue new requests when the NAT thread is about to stop */
249 if (pThis->pThread->enmState != PDMTHREADSTATE_RUNNING)
250 return;
251 int rc = RTReqAlloc(pThis->pReqQueue, &pReq, RTREQTYPE_INTERNAL);
252 AssertReleaseRC(rc);
253 pReq->u.Internal.pfn = (PFNRT)drvNATNotifyLinkChangedWorker;
254 pReq->u.Internal.cArgs = 2;
255 pReq->u.Internal.aArgs[0] = (uintptr_t)pThis;
256 pReq->u.Internal.aArgs[1] = (uintptr_t)enmLinkState;
257 pReq->fFlags = RTREQFLAGS_VOID;
258 rc = RTReqQueue(pReq, 0); /* don't wait, we have to wakeup the NAT thread fist */
259 if (RT_LIKELY(rc == VERR_TIMEOUT))
260 {
261# ifndef RT_OS_WINDOWS
262 /* kick select() */
263 rc = RTFileWrite(pThis->PipeWrite, "", 1, NULL);
264 AssertRC(rc);
265# else
266 /* kick WSAWaitForMultipleEvents() */
267 rc = WSASetEvent(pThis->hWakeupEvent);
268 AssertRelease(rc == TRUE);
269# endif
270 rc = RTReqWait(pReq, RT_INDEFINITE_WAIT);
271 AssertReleaseRC(rc);
272 }
273 else
274 AssertReleaseRC(rc);
275 RTReqFree(pReq);
276
277#else /* !VBOX_WITH_SIMPLIFIED_SLIRP_SYNC */
278
279 int rc = RTCritSectEnter(&pThis->CritSect);
280 AssertReleaseRC(rc);
281 drvNATNotifyLinkChangedWorker(pThis, enmLinkState);
282 RTCritSectLeave(&pThis->CritSect);
283
284#endif /* VBOX_WITH_SIMPLIFIED_SLIRP_SYNC */
285}
286
287
288#ifndef VBOX_WITH_SIMPLIFIED_SLIRP_SYNC
289
290/**
291 * Poller callback.
292 */
293static DECLCALLBACK(void) drvNATPoller(PPDMDRVINS pDrvIns)
294{
295 PDRVNAT pThis = PDMINS_2_DATA(pDrvIns, PDRVNAT);
296 fd_set ReadFDs;
297 fd_set WriteFDs;
298 fd_set XcptFDs;
299 int nFDs = -1;
300 FD_ZERO(&ReadFDs);
301 FD_ZERO(&WriteFDs);
302 FD_ZERO(&XcptFDs);
303
304 int rc = RTCritSectEnter(&pThis->CritSect);
305 AssertReleaseRC(rc);
306
307 slirp_select_fill(pThis->pNATState, &nFDs, &ReadFDs, &WriteFDs, &XcptFDs);
308
309 struct timeval tv = {0, 0}; /* no wait */
310 int cChangedFDs = select(nFDs + 1, &ReadFDs, &WriteFDs, &XcptFDs, &tv);
311 if (cChangedFDs >= 0)
312 slirp_select_poll(pThis->pNATState, &ReadFDs, &WriteFDs, &XcptFDs);
313
314 RTCritSectLeave(&pThis->CritSect);
315}
316
317#else /* VBOX_WITH_SIMPLIFIED_SLIRP_SYNC */
318
319static DECLCALLBACK(int) drvNATAsyncIoThread(PPDMDRVINS pDrvIns, PPDMTHREAD pThread)
320{
321 PDRVNAT pThis = PDMINS_2_DATA(pDrvIns, PDRVNAT);
322 fd_set ReadFDs;
323 fd_set WriteFDs;
324 fd_set XcptFDs;
325 int nFDs = -1;
326 unsigned int ms;
327# ifdef RT_OS_WINDOWS
328 DWORD event;
329 HANDLE *phEvents;
330# endif
331
332 LogFlow(("drvNATAsyncIoThread: pThis=%p\n", pThis));
333
334 if (pThread->enmState == PDMTHREADSTATE_INITIALIZING)
335 return VINF_SUCCESS;
336
337#ifdef RT_OS_WINDOWS
338 phEvents = slirp_get_events(pThis->pNATState);
339#endif
340
341 /*
342 * Polling loop.
343 */
344 while (pThread->enmState == PDMTHREADSTATE_RUNNING)
345 {
346 FD_ZERO(&ReadFDs);
347 FD_ZERO(&WriteFDs);
348 FD_ZERO(&XcptFDs);
349 nFDs = -1;
350
351 /*
352 * To prevent concurent execution of sending/receving threads
353 */
354 slirp_select_fill(pThis->pNATState, &nFDs, &ReadFDs, &WriteFDs, &XcptFDs);
355 ms = slirp_get_timeout_ms(pThis->pNATState);
356# ifndef RT_OS_WINDOWS
357 struct timeval tv = { 0, ms*1000 };
358 FD_SET(pThis->PipeRead, &ReadFDs);
359 nFDs = ((int)pThis->PipeRead < nFDs ? nFDs : pThis->PipeRead);
360 int cChangedFDs = select(nFDs + 1, &ReadFDs, &WriteFDs, &XcptFDs, ms ? &tv : NULL);
361 if (cChangedFDs >= 0)
362 {
363 slirp_select_poll(pThis->pNATState, &ReadFDs, &WriteFDs, &XcptFDs);
364 if (FD_ISSET(pThis->PipeRead, &ReadFDs))
365 {
366 /* drain the pipe */
367 char ch[1];
368 size_t cbRead;
369 RTFileRead(pThis->PipeRead, &ch, 1, &cbRead);
370 }
371 /* process _all_ outstanding requests but don't wait */
372 RTReqProcess(pThis->pReqQueue, 0);
373 }
374# else /* RT_OS_WINDOWS */
375 event = WSAWaitForMultipleEvents(nFDs, phEvents, FALSE, ms ? ms : WSA_INFINITE, FALSE);
376 if ( (event < WSA_WAIT_EVENT_0 || event > WSA_WAIT_EVENT_0 + nFDs - 1)
377 && event != WSA_WAIT_TIMEOUT)
378 {
379 int error = WSAGetLastError();
380 LogRel(("WSAWaitForMultipleEvents returned %d (error %d)\n", event, error));
381 RTAssertReleasePanic();
382 }
383
384 if (event == WSA_WAIT_TIMEOUT)
385 {
386 /* only check for slow/fast timers */
387 slirp_select_poll(pThis->pNATState, /* fTimeout=*/true, /*fIcmp=*/false);
388 continue;
389 }
390
391 /* poll the sockets in any case */
392 slirp_select_poll(pThis->pNATState, /* fTimeout=*/false, /* fIcmp=*/(event == WSA_WAIT_EVENT_0));
393 /* process _all_ outstanding requests but don't wait */
394 RTReqProcess(pThis->pReqQueue, 0);
395# endif /* RT_OS_WINDOWS */
396 }
397
398 return VINF_SUCCESS;
399}
400
401 /**
402 * Unblock the send thread so it can respond to a state change.
403 *
404 * @returns VBox status code.
405 * @param pDevIns The pcnet device instance.
406 * @param pThread The send thread.
407 */
408static DECLCALLBACK(int) drvNATAsyncIoWakeup(PPDMDRVINS pDrvIns, PPDMTHREAD pThread)
409{
410 PDRVNAT pThis = PDMINS_2_DATA(pDrvIns, PDRVNAT);
411
412# ifndef RT_OS_WINDOWS
413 /* kick select() */
414 int rc = RTFileWrite(pThis->PipeWrite, "", 1, NULL);
415 AssertRC(rc);
416# else
417 /* kick WSAWaitForMultipleEvents() */
418 WSASetEvent(pThis->hWakeupEvent);
419# endif
420
421 return VINF_SUCCESS;
422}
423
424#endif /* VBOX_WITH_SIMPLIFIED_SLIRP_SYNC */
425
426
427/**
428 * Function called by slirp to check if it's possible to feed incoming data to the network port.
429 * @returns 1 if possible.
430 * @returns 0 if not possible.
431 */
432int slirp_can_output(void *pvUser)
433{
434 PDRVNAT pThis = (PDRVNAT)pvUser;
435
436 Assert(pThis);
437
438#ifndef VBOX_WITH_SIMPLIFIED_SLIRP_SYNC
439 /** Happens during termination */
440 if (!RTCritSectIsOwner(&pThis->CritSect))
441 return 0;
442
443 int rc = pThis->pPort->pfnWaitReceiveAvail(pThis->pPort, 0);
444 return RT_SUCCESS(rc);
445#else
446 return 1;
447#endif
448}
449
450
451/**
452 * Function called by slirp to feed incoming data to the network port.
453 */
454void slirp_output(void *pvUser, const uint8_t *pu8Buf, int cb)
455{
456 PDRVNAT pThis = (PDRVNAT)pvUser;
457
458 LogFlow(("slirp_output BEGIN %x %d\n", pu8Buf, cb));
459 Log2(("slirp_output: pu8Buf=%p cb=%#x (pThis=%p)\n%.*Rhxd\n", pu8Buf, cb, pThis, cb, pu8Buf));
460
461 Assert(pThis);
462
463#ifndef VBOX_WITH_SIMPLIFIED_SLIRP_SYNC
464 /** Happens during termination */
465 if (!RTCritSectIsOwner(&pThis->CritSect))
466 return;
467
468 int rc = pThis->pPort->pfnReceive(pThis->pPort, pu8Buf, cb);
469 AssertRC(rc);
470 LogFlow(("slirp_output END %x %d\n", pu8Buf, cb));
471#else
472
473 PDRVNATQUEUITEM pItem = (PDRVNATQUEUITEM)PDMQueueAlloc(pThis->pSendQueue);
474 if (pItem)
475 {
476 pItem->pu8Buf = pu8Buf;
477 pItem->cb = cb;
478 Log2(("pItem:%p %.Rhxd\n", pItem, pItem->pu8Buf));
479 PDMQueueInsert(pThis->pSendQueue, &pItem->Core);
480 return;
481 }
482#endif
483}
484
485#ifdef VBOX_WITH_SIMPLIFIED_SLIRP_SYNC
486/**
487 * Queue callback for processing a queued item.
488 *
489 * @returns Success indicator.
490 * If false the item will not be removed and the flushing will stop.
491 * @param pDrvIns The driver instance.
492 * @param pItemCore Pointer to the queue item to process.
493 */
494static DECLCALLBACK(bool) drvNATQueueConsumer(PPDMDRVINS pDrvIns, PPDMQUEUEITEMCORE pItemCore)
495{
496 PDRVNAT pThis = PDMINS_2_DATA(pDrvIns, PDRVNAT);
497 PDRVNATQUEUITEM pItem = (PDRVNATQUEUITEM)pItemCore;
498 Log(("drvNATQueueConsumer(pItem:%p, pu8Buf:%p, cb:%d)\n", pItem, pItem->pu8Buf, pItem->cb));
499 Log2(("drvNATQueueConsumer: pu8Buf:\n%.Rhxd\n", pItem->pu8Buf));
500 int rc = pThis->pPort->pfnWaitReceiveAvail(pThis->pPort, 0);
501 if (RT_FAILURE(rc))
502 return false;
503 rc = pThis->pPort->pfnReceive(pThis->pPort, pItem->pu8Buf, pItem->cb);
504 AssertRC(rc);
505 RTMemFree((void *)pItem->pu8Buf); /* XXX: shouldn't free buffer here */
506 return RT_SUCCESS(rc);
507}
508#endif
509
510/**
511 * Queries an interface to the driver.
512 *
513 * @returns Pointer to interface.
514 * @returns NULL if the interface was not supported by the driver.
515 * @param pInterface Pointer to this interface structure.
516 * @param enmInterface The requested interface identification.
517 * @thread Any thread.
518 */
519static DECLCALLBACK(void *) drvNATQueryInterface(PPDMIBASE pInterface, PDMINTERFACE enmInterface)
520{
521 PPDMDRVINS pDrvIns = PDMIBASE_2_PDMDRV(pInterface);
522 PDRVNAT pThis = PDMINS_2_DATA(pDrvIns, PDRVNAT);
523 switch (enmInterface)
524 {
525 case PDMINTERFACE_BASE:
526 return &pDrvIns->IBase;
527 case PDMINTERFACE_NETWORK_CONNECTOR:
528 return &pThis->INetworkConnector;
529 default:
530 return NULL;
531 }
532}
533
534
535/**
536 * Destruct a driver instance.
537 *
538 * Most VM resources are freed by the VM. This callback is provided so that any non-VM
539 * resources can be freed correctly.
540 *
541 * @param pDrvIns The driver instance data.
542 */
543static DECLCALLBACK(void) drvNATDestruct(PPDMDRVINS pDrvIns)
544{
545 PDRVNAT pThis = PDMINS_2_DATA(pDrvIns, PDRVNAT);
546
547 LogFlow(("drvNATDestruct:\n"));
548
549#ifndef VBOX_WITH_SIMPLIFIED_SLIRP_SYNC
550 int rc = RTCritSectEnter(&pThis->CritSect);
551 AssertReleaseRC(rc);
552#endif
553 slirp_term(pThis->pNATState);
554 pThis->pNATState = NULL;
555#ifndef VBOX_WITH_SIMPLIFIED_SLIRP_SYNC
556 RTCritSectLeave(&pThis->CritSect);
557 RTCritSectDelete(&pThis->CritSect);
558#endif
559}
560
561
562/**
563 * Sets up the redirectors.
564 *
565 * @returns VBox status code.
566 * @param pCfgHandle The drivers configuration handle.
567 */
568static int drvNATConstructRedir(unsigned iInstance, PDRVNAT pThis, PCFGMNODE pCfgHandle, RTIPV4ADDR Network)
569{
570 /*
571 * Enumerate redirections.
572 */
573 for (PCFGMNODE pNode = CFGMR3GetFirstChild(pCfgHandle); pNode; pNode = CFGMR3GetNextChild(pNode))
574 {
575 /*
576 * Validate the port forwarding config.
577 */
578 if (!CFGMR3AreValuesValid(pNode, "Protocol\0UDP\0HostPort\0GuestPort\0GuestIP\0"))
579 return PDMDRV_SET_ERROR(pThis->pDrvIns, VERR_PDM_DRVINS_UNKNOWN_CFG_VALUES, N_("Unknown configuration in port forwarding"));
580
581 /* protocol type */
582 bool fUDP;
583 char szProtocol[32];
584 int rc = CFGMR3QueryString(pNode, "Protocol", &szProtocol[0], sizeof(szProtocol));
585 if (rc == VERR_CFGM_VALUE_NOT_FOUND)
586 {
587 rc = CFGMR3QueryBool(pNode, "UDP", &fUDP);
588 if (rc == VERR_CFGM_VALUE_NOT_FOUND)
589 fUDP = false;
590 else if (RT_FAILURE(rc))
591 return PDMDrvHlpVMSetError(pThis->pDrvIns, rc, RT_SRC_POS, N_("NAT#%d: configuration query for \"UDP\" boolean failed"), iInstance);
592 }
593 else if (RT_SUCCESS(rc))
594 {
595 if (!RTStrICmp(szProtocol, "TCP"))
596 fUDP = false;
597 else if (!RTStrICmp(szProtocol, "UDP"))
598 fUDP = true;
599 else
600 return PDMDrvHlpVMSetError(pThis->pDrvIns, VERR_INVALID_PARAMETER, RT_SRC_POS, N_("NAT#%d: Invalid configuration value for \"Protocol\": \"%s\""), iInstance, szProtocol);
601 }
602 else
603 return PDMDrvHlpVMSetError(pThis->pDrvIns, rc, RT_SRC_POS, N_("NAT#%d: configuration query for \"Protocol\" string failed"), iInstance);
604
605 /* host port */
606 int32_t iHostPort;
607 rc = CFGMR3QueryS32(pNode, "HostPort", &iHostPort);
608 if (RT_FAILURE(rc))
609 return PDMDrvHlpVMSetError(pThis->pDrvIns, rc, RT_SRC_POS, N_("NAT#%d: configuration query for \"HostPort\" integer failed"), iInstance);
610
611 /* guest port */
612 int32_t iGuestPort;
613 rc = CFGMR3QueryS32(pNode, "GuestPort", &iGuestPort);
614 if (RT_FAILURE(rc))
615 return PDMDrvHlpVMSetError(pThis->pDrvIns, rc, RT_SRC_POS, N_("NAT#%d: configuration query for \"GuestPort\" integer failed"), iInstance);
616
617 /* guest address */
618 char szGuestIP[32];
619 rc = CFGMR3QueryString(pNode, "GuestIP", &szGuestIP[0], sizeof(szGuestIP));
620 if (rc == VERR_CFGM_VALUE_NOT_FOUND)
621 RTStrPrintf(szGuestIP, sizeof(szGuestIP), "%d.%d.%d.%d",
622 (Network & 0xFF000000) >> 24, (Network & 0xFF0000) >> 16, (Network & 0xFF00) >> 8, (Network & 0xE0) | 15);
623 else if (RT_FAILURE(rc))
624 return PDMDrvHlpVMSetError(pThis->pDrvIns, rc, RT_SRC_POS, N_("NAT#%d: configuration query for \"GuestIP\" string failed"), iInstance);
625 struct in_addr GuestIP;
626 if (!inet_aton(szGuestIP, &GuestIP))
627 return PDMDrvHlpVMSetError(pThis->pDrvIns, VERR_NAT_REDIR_GUEST_IP, RT_SRC_POS,
628 N_("NAT#%d: configuration error: invalid \"GuestIP\"=\"%s\", inet_aton failed"), iInstance, szGuestIP);
629
630 /*
631 * Call slirp about it.
632 */
633 Log(("drvNATConstruct: Redir %d -> %s:%d\n", iHostPort, szGuestIP, iGuestPort));
634 if (slirp_redir(pThis->pNATState, fUDP, iHostPort, GuestIP, iGuestPort) < 0)
635 return PDMDrvHlpVMSetError(pThis->pDrvIns, VERR_NAT_REDIR_SETUP, RT_SRC_POS,
636 N_("NAT#%d: configuration error: failed to set up redirection of %d to %s:%d. Probably a conflict with existing services or other rules"), iInstance, iHostPort, szGuestIP, iGuestPort);
637 } /* for each redir rule */
638
639 return VINF_SUCCESS;
640}
641
642/**
643 * Get the MAC address into the slirp stack.
644 */
645static void drvNATSetMac(PDRVNAT pThis)
646{
647 if (pThis->pConfig)
648 {
649 RTMAC Mac;
650 pThis->pConfig->pfnGetMac(pThis->pConfig, &Mac);
651 slirp_set_ethaddr(pThis->pNATState, Mac.au8);
652 }
653}
654
655
656/**
657 * After loading we have to pass the MAC address of the ethernet device to the slirp stack.
658 * Otherwise the guest is not reachable until it performs a DHCP request or an ARP request
659 * (usually done during guest boot).
660 */
661static DECLCALLBACK(int) drvNATLoadDone(PPDMDRVINS pDrvIns, PSSMHANDLE pSSMHandle)
662{
663 PDRVNAT pThis = PDMINS_2_DATA(pDrvIns, PDRVNAT);
664 drvNATSetMac(pThis);
665 return VINF_SUCCESS;
666}
667
668
669/**
670 * Some guests might not use DHCP to retrieve an IP but use a static IP.
671 */
672static DECLCALLBACK(void) drvNATPowerOn(PPDMDRVINS pDrvIns)
673{
674 PDRVNAT pThis = PDMINS_2_DATA(pDrvIns, PDRVNAT);
675 drvNATSetMac(pThis);
676}
677
678
679/**
680 * Construct a NAT network transport driver instance.
681 *
682 * @returns VBox status.
683 * @param pDrvIns The driver instance data.
684 * If the registration structure is needed, pDrvIns->pDrvReg points to it.
685 * @param pCfgHandle Configuration node handle for the driver. Use this to obtain the configuration
686 * of the driver instance. It's also found in pDrvIns->pCfgHandle, but like
687 * iInstance it's expected to be used a bit in this function.
688 */
689static DECLCALLBACK(int) drvNATConstruct(PPDMDRVINS pDrvIns, PCFGMNODE pCfgHandle)
690{
691 PDRVNAT pThis = PDMINS_2_DATA(pDrvIns, PDRVNAT);
692 char szNetAddr[16];
693 char szNetwork[32]; /* xxx.xxx.xxx.xxx/yy */
694 LogFlow(("drvNATConstruct:\n"));
695
696 /*
697 * Validate the config.
698 */
699 if (!CFGMR3AreValuesValid(pCfgHandle, "PassDomain\0TFTPPrefix\0BootFile\0Network\0"))
700 return PDMDRV_SET_ERROR(pDrvIns, VERR_PDM_DRVINS_UNKNOWN_CFG_VALUES, N_("Unknown NAT configuration option, only supports PassDomain, TFTPPrefix, BootFile and Network"));
701
702 /*
703 * Init the static parts.
704 */
705 pThis->pDrvIns = pDrvIns;
706 pThis->pNATState = NULL;
707 pThis->pszTFTPPrefix = NULL;
708 pThis->pszBootFile = NULL;
709 /* IBase */
710 pDrvIns->IBase.pfnQueryInterface = drvNATQueryInterface;
711 /* INetwork */
712 pThis->INetworkConnector.pfnSend = drvNATSend;
713 pThis->INetworkConnector.pfnSetPromiscuousMode = drvNATSetPromiscuousMode;
714 pThis->INetworkConnector.pfnNotifyLinkChanged = drvNATNotifyLinkChanged;
715
716 /*
717 * Get the configuration settings.
718 */
719 bool fPassDomain = true;
720 int rc = CFGMR3QueryBool(pCfgHandle, "PassDomain", &fPassDomain);
721 if (rc == VERR_CFGM_VALUE_NOT_FOUND)
722 fPassDomain = true;
723 else if (RT_FAILURE(rc))
724 return PDMDrvHlpVMSetError(pDrvIns, rc, RT_SRC_POS, N_("NAT#%d: configuration query for \"PassDomain\" boolean failed"), pDrvIns->iInstance);
725
726 rc = CFGMR3QueryStringAlloc(pCfgHandle, "TFTPPrefix", &pThis->pszTFTPPrefix);
727 if (RT_FAILURE(rc) && rc != VERR_CFGM_VALUE_NOT_FOUND)
728 return PDMDrvHlpVMSetError(pDrvIns, rc, RT_SRC_POS, N_("NAT#%d: configuration query for \"TFTPPrefix\" string failed"), pDrvIns->iInstance);
729 rc = CFGMR3QueryStringAlloc(pCfgHandle, "BootFile", &pThis->pszBootFile);
730 if (RT_FAILURE(rc) && rc != VERR_CFGM_VALUE_NOT_FOUND)
731 return PDMDrvHlpVMSetError(pDrvIns, rc, RT_SRC_POS, N_("NAT#%d: configuration query for \"BootFile\" string failed"), pDrvIns->iInstance);
732
733 /*
734 * Query the network port interface.
735 */
736 pThis->pPort = (PPDMINETWORKPORT)pDrvIns->pUpBase->pfnQueryInterface(pDrvIns->pUpBase, PDMINTERFACE_NETWORK_PORT);
737 if (!pThis->pPort)
738 return PDMDRV_SET_ERROR(pDrvIns, VERR_PDM_MISSING_INTERFACE_ABOVE,
739 N_("Configuration error: the above device/driver didn't export the network port interface"));
740 pThis->pConfig = (PPDMINETWORKCONFIG)pDrvIns->pUpBase->pfnQueryInterface(pDrvIns->pUpBase, PDMINTERFACE_NETWORK_CONFIG);
741 if (!pThis->pConfig)
742 return PDMDRV_SET_ERROR(pDrvIns, VERR_PDM_MISSING_INTERFACE_ABOVE,
743 N_("Configuration error: the above device/driver didn't export the network config interface"));
744
745 /* Generate a network address for this network card. */
746 rc = CFGMR3QueryString(pCfgHandle, "Network", szNetwork, sizeof(szNetwork));
747 if (rc == VERR_CFGM_VALUE_NOT_FOUND)
748 RTStrPrintf(szNetwork, sizeof(szNetwork), "10.0.%d.0/24", pDrvIns->iInstance + 2);
749 else if (RT_FAILURE(rc))
750 return PDMDrvHlpVMSetError(pDrvIns, rc, RT_SRC_POS, N_("NAT#%d: configuration query for \"Network\" string failed"), pDrvIns->iInstance);
751
752 RTIPV4ADDR Network;
753 RTIPV4ADDR Netmask;
754 rc = RTCidrStrToIPv4(szNetwork, &Network, &Netmask);
755 if (RT_FAILURE(rc))
756 return PDMDrvHlpVMSetError(pDrvIns, rc, RT_SRC_POS, N_("NAT#%d: Configuration error: network '%s' describes not a valid IPv4 network"), pDrvIns->iInstance, szNetwork);
757
758 RTStrPrintf(szNetAddr, sizeof(szNetAddr), "%d.%d.%d.%d",
759 (Network & 0xFF000000) >> 24, (Network & 0xFF0000) >> 16, (Network & 0xFF00) >> 8, Network & 0xFF);
760
761 /*
762 * The slirp lock..
763 */
764#ifndef VBOX_WITH_SIMPLIFIED_SLIRP_SYNC
765 rc = RTCritSectInit(&pThis->CritSect);
766 if (RT_FAILURE(rc))
767 return rc;
768#endif
769 /*
770 * Initialize slirp.
771 */
772 rc = slirp_init(&pThis->pNATState, &szNetAddr[0], Netmask, fPassDomain, pThis->pszTFTPPrefix, pThis->pszBootFile, pThis);
773 if (RT_SUCCESS(rc))
774 {
775 slirp_register_timers(pThis->pNATState, pDrvIns);
776 int rc2 = drvNATConstructRedir(pDrvIns->iInstance, pThis, pCfgHandle, Network);
777 if (RT_SUCCESS(rc2))
778 {
779 /*
780 * Register a load done notification to get the MAC address into the slirp
781 * engine after we loaded a guest state.
782 */
783 rc2 = PDMDrvHlpSSMRegister(pDrvIns, pDrvIns->pDrvReg->szDriverName,
784 pDrvIns->iInstance, 0, 0,
785 NULL, NULL, NULL, NULL, NULL, drvNATLoadDone);
786 AssertRC(rc2);
787#ifndef VBOX_WITH_SIMPLIFIED_SLIRP_SYNC
788 pDrvIns->pDrvHlp->pfnPDMPollerRegister(pDrvIns, drvNATPoller);
789#else
790 rc = RTReqCreateQueue(&pThis->pReqQueue);
791 if (RT_FAILURE(rc))
792 {
793 LogRel(("Can't create request queue\n"));
794 return rc;
795 }
796
797 rc = pDrvIns->pDrvHlp->pfnPDMQueueCreate(pDrvIns, sizeof(DRVNATQUEUITEM), 50, 0, drvNATQueueConsumer, &pThis->pSendQueue);
798 if (RT_FAILURE(rc))
799 {
800 LogRel(("Can't create send queue\n"));
801 return rc;
802 }
803
804# ifndef RT_OS_WINDOWS
805 /*
806 * Create the control pipe.
807 */
808 int fds[2];
809 if (pipe(&fds[0]) != 0) /** @todo RTPipeCreate() or something... */
810 {
811 int rc = RTErrConvertFromErrno(errno);
812 AssertRC(rc);
813 return rc;
814 }
815 pThis->PipeRead = fds[0];
816 pThis->PipeWrite = fds[1];
817# else
818 pThis->hWakeupEvent = CreateEvent(NULL, FALSE, FALSE, NULL); /* auto-reset event */
819 slirp_register_external_event(pThis->pNATState, pThis->hWakeupEvent, VBOX_WAKEUP_EVENT_INDEX);
820# endif
821
822 rc = PDMDrvHlpPDMThreadCreate(pDrvIns, &pThis->pThread, pThis, drvNATAsyncIoThread, drvNATAsyncIoWakeup, 128 * _1K, RTTHREADTYPE_IO, "NAT");
823 AssertReleaseRC(rc);
824#endif
825
826 pThis->enmLinkState = PDMNETWORKLINKSTATE_UP;
827
828 /* might return VINF_NAT_DNS */
829 return rc;
830 }
831 /* failure path */
832 rc = rc2;
833 slirp_term(pThis->pNATState);
834 pThis->pNATState = NULL;
835 }
836 else
837 {
838 PDMDRV_SET_ERROR(pDrvIns, rc, N_("Unknown error during NAT networking setup: "));
839 AssertMsgFailed(("Add error message for rc=%d (%Rrc)\n", rc, rc));
840 }
841
842#ifndef VBOX_WITH_SIMPLIFIED_SLIRP_SYNC
843 RTCritSectDelete(&pThis->CritSect);
844#endif
845 return rc;
846}
847
848
849/**
850 * NAT network transport driver registration record.
851 */
852const PDMDRVREG g_DrvNAT =
853{
854 /* u32Version */
855 PDM_DRVREG_VERSION,
856 /* szDriverName */
857 "NAT",
858 /* pszDescription */
859 "NAT Network Transport Driver",
860 /* fFlags */
861 PDM_DRVREG_FLAGS_HOST_BITS_DEFAULT,
862 /* fClass. */
863 PDM_DRVREG_CLASS_NETWORK,
864 /* cMaxInstances */
865 16,
866 /* cbInstance */
867 sizeof(DRVNAT),
868 /* pfnConstruct */
869 drvNATConstruct,
870 /* pfnDestruct */
871 drvNATDestruct,
872 /* pfnIOCtl */
873 NULL,
874 /* pfnPowerOn */
875 drvNATPowerOn,
876 /* pfnReset */
877 NULL,
878 /* pfnSuspend */
879 NULL,
880 /* pfnResume */
881 NULL,
882 /* pfnDetach */
883 NULL,
884 /* pfnPowerOff */
885 NULL
886};
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