VirtualBox

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

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

slirp: send to guest is queued

  • 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 RT_FAILURE(rc);
503 }
504 rc = pThis->pPort->pfnReceive(pThis->pPort, pItem->pu8Buf, pItem->cb);
505 AssertRC(rc);
506 RTMemFree((void *)pItem->pu8Buf); /* XXX: shouldn't free buffer here */
507 return RT_SUCCESS(rc);
508}
509#endif
510
511/**
512 * Queries an interface to the driver.
513 *
514 * @returns Pointer to interface.
515 * @returns NULL if the interface was not supported by the driver.
516 * @param pInterface Pointer to this interface structure.
517 * @param enmInterface The requested interface identification.
518 * @thread Any thread.
519 */
520static DECLCALLBACK(void *) drvNATQueryInterface(PPDMIBASE pInterface, PDMINTERFACE enmInterface)
521{
522 PPDMDRVINS pDrvIns = PDMIBASE_2_PDMDRV(pInterface);
523 PDRVNAT pThis = PDMINS_2_DATA(pDrvIns, PDRVNAT);
524 switch (enmInterface)
525 {
526 case PDMINTERFACE_BASE:
527 return &pDrvIns->IBase;
528 case PDMINTERFACE_NETWORK_CONNECTOR:
529 return &pThis->INetworkConnector;
530 default:
531 return NULL;
532 }
533}
534
535
536/**
537 * Destruct a driver instance.
538 *
539 * Most VM resources are freed by the VM. This callback is provided so that any non-VM
540 * resources can be freed correctly.
541 *
542 * @param pDrvIns The driver instance data.
543 */
544static DECLCALLBACK(void) drvNATDestruct(PPDMDRVINS pDrvIns)
545{
546 PDRVNAT pThis = PDMINS_2_DATA(pDrvIns, PDRVNAT);
547
548 LogFlow(("drvNATDestruct:\n"));
549
550#ifndef VBOX_WITH_SIMPLIFIED_SLIRP_SYNC
551 int rc = RTCritSectEnter(&pThis->CritSect);
552 AssertReleaseRC(rc);
553#endif
554 slirp_term(pThis->pNATState);
555 pThis->pNATState = NULL;
556#ifndef VBOX_WITH_SIMPLIFIED_SLIRP_SYNC
557 RTCritSectLeave(&pThis->CritSect);
558 RTCritSectDelete(&pThis->CritSect);
559#endif
560}
561
562
563/**
564 * Sets up the redirectors.
565 *
566 * @returns VBox status code.
567 * @param pCfgHandle The drivers configuration handle.
568 */
569static int drvNATConstructRedir(unsigned iInstance, PDRVNAT pThis, PCFGMNODE pCfgHandle, RTIPV4ADDR Network)
570{
571 /*
572 * Enumerate redirections.
573 */
574 for (PCFGMNODE pNode = CFGMR3GetFirstChild(pCfgHandle); pNode; pNode = CFGMR3GetNextChild(pNode))
575 {
576 /*
577 * Validate the port forwarding config.
578 */
579 if (!CFGMR3AreValuesValid(pNode, "Protocol\0UDP\0HostPort\0GuestPort\0GuestIP\0"))
580 return PDMDRV_SET_ERROR(pThis->pDrvIns, VERR_PDM_DRVINS_UNKNOWN_CFG_VALUES, N_("Unknown configuration in port forwarding"));
581
582 /* protocol type */
583 bool fUDP;
584 char szProtocol[32];
585 int rc = CFGMR3QueryString(pNode, "Protocol", &szProtocol[0], sizeof(szProtocol));
586 if (rc == VERR_CFGM_VALUE_NOT_FOUND)
587 {
588 rc = CFGMR3QueryBool(pNode, "UDP", &fUDP);
589 if (rc == VERR_CFGM_VALUE_NOT_FOUND)
590 fUDP = false;
591 else if (RT_FAILURE(rc))
592 return PDMDrvHlpVMSetError(pThis->pDrvIns, rc, RT_SRC_POS, N_("NAT#%d: configuration query for \"UDP\" boolean failed"), iInstance);
593 }
594 else if (RT_SUCCESS(rc))
595 {
596 if (!RTStrICmp(szProtocol, "TCP"))
597 fUDP = false;
598 else if (!RTStrICmp(szProtocol, "UDP"))
599 fUDP = true;
600 else
601 return PDMDrvHlpVMSetError(pThis->pDrvIns, VERR_INVALID_PARAMETER, RT_SRC_POS, N_("NAT#%d: Invalid configuration value for \"Protocol\": \"%s\""), iInstance, szProtocol);
602 }
603 else
604 return PDMDrvHlpVMSetError(pThis->pDrvIns, rc, RT_SRC_POS, N_("NAT#%d: configuration query for \"Protocol\" string failed"), iInstance);
605
606 /* host port */
607 int32_t iHostPort;
608 rc = CFGMR3QueryS32(pNode, "HostPort", &iHostPort);
609 if (RT_FAILURE(rc))
610 return PDMDrvHlpVMSetError(pThis->pDrvIns, rc, RT_SRC_POS, N_("NAT#%d: configuration query for \"HostPort\" integer failed"), iInstance);
611
612 /* guest port */
613 int32_t iGuestPort;
614 rc = CFGMR3QueryS32(pNode, "GuestPort", &iGuestPort);
615 if (RT_FAILURE(rc))
616 return PDMDrvHlpVMSetError(pThis->pDrvIns, rc, RT_SRC_POS, N_("NAT#%d: configuration query for \"GuestPort\" integer failed"), iInstance);
617
618 /* guest address */
619 char szGuestIP[32];
620 rc = CFGMR3QueryString(pNode, "GuestIP", &szGuestIP[0], sizeof(szGuestIP));
621 if (rc == VERR_CFGM_VALUE_NOT_FOUND)
622 RTStrPrintf(szGuestIP, sizeof(szGuestIP), "%d.%d.%d.%d",
623 (Network & 0xFF000000) >> 24, (Network & 0xFF0000) >> 16, (Network & 0xFF00) >> 8, (Network & 0xE0) | 15);
624 else if (RT_FAILURE(rc))
625 return PDMDrvHlpVMSetError(pThis->pDrvIns, rc, RT_SRC_POS, N_("NAT#%d: configuration query for \"GuestIP\" string failed"), iInstance);
626 struct in_addr GuestIP;
627 if (!inet_aton(szGuestIP, &GuestIP))
628 return PDMDrvHlpVMSetError(pThis->pDrvIns, VERR_NAT_REDIR_GUEST_IP, RT_SRC_POS,
629 N_("NAT#%d: configuration error: invalid \"GuestIP\"=\"%s\", inet_aton failed"), iInstance, szGuestIP);
630
631 /*
632 * Call slirp about it.
633 */
634 Log(("drvNATConstruct: Redir %d -> %s:%d\n", iHostPort, szGuestIP, iGuestPort));
635 if (slirp_redir(pThis->pNATState, fUDP, iHostPort, GuestIP, iGuestPort) < 0)
636 return PDMDrvHlpVMSetError(pThis->pDrvIns, VERR_NAT_REDIR_SETUP, RT_SRC_POS,
637 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);
638 } /* for each redir rule */
639
640 return VINF_SUCCESS;
641}
642
643/**
644 * Get the MAC address into the slirp stack.
645 */
646static void drvNATSetMac(PDRVNAT pThis)
647{
648 if (pThis->pConfig)
649 {
650 RTMAC Mac;
651 pThis->pConfig->pfnGetMac(pThis->pConfig, &Mac);
652 slirp_set_ethaddr(pThis->pNATState, Mac.au8);
653 }
654}
655
656
657/**
658 * After loading we have to pass the MAC address of the ethernet device to the slirp stack.
659 * Otherwise the guest is not reachable until it performs a DHCP request or an ARP request
660 * (usually done during guest boot).
661 */
662static DECLCALLBACK(int) drvNATLoadDone(PPDMDRVINS pDrvIns, PSSMHANDLE pSSMHandle)
663{
664 PDRVNAT pThis = PDMINS_2_DATA(pDrvIns, PDRVNAT);
665 drvNATSetMac(pThis);
666 return VINF_SUCCESS;
667}
668
669
670/**
671 * Some guests might not use DHCP to retrieve an IP but use a static IP.
672 */
673static DECLCALLBACK(void) drvNATPowerOn(PPDMDRVINS pDrvIns)
674{
675 PDRVNAT pThis = PDMINS_2_DATA(pDrvIns, PDRVNAT);
676 drvNATSetMac(pThis);
677}
678
679
680/**
681 * Construct a NAT network transport driver instance.
682 *
683 * @returns VBox status.
684 * @param pDrvIns The driver instance data.
685 * If the registration structure is needed, pDrvIns->pDrvReg points to it.
686 * @param pCfgHandle Configuration node handle for the driver. Use this to obtain the configuration
687 * of the driver instance. It's also found in pDrvIns->pCfgHandle, but like
688 * iInstance it's expected to be used a bit in this function.
689 */
690static DECLCALLBACK(int) drvNATConstruct(PPDMDRVINS pDrvIns, PCFGMNODE pCfgHandle)
691{
692 PDRVNAT pThis = PDMINS_2_DATA(pDrvIns, PDRVNAT);
693 char szNetAddr[16];
694 char szNetwork[32]; /* xxx.xxx.xxx.xxx/yy */
695 LogFlow(("drvNATConstruct:\n"));
696
697 /*
698 * Validate the config.
699 */
700 if (!CFGMR3AreValuesValid(pCfgHandle, "PassDomain\0TFTPPrefix\0BootFile\0Network\0"))
701 return PDMDRV_SET_ERROR(pDrvIns, VERR_PDM_DRVINS_UNKNOWN_CFG_VALUES, N_("Unknown NAT configuration option, only supports PassDomain, TFTPPrefix, BootFile and Network"));
702
703 /*
704 * Init the static parts.
705 */
706 pThis->pDrvIns = pDrvIns;
707 pThis->pNATState = NULL;
708 pThis->pszTFTPPrefix = NULL;
709 pThis->pszBootFile = NULL;
710 /* IBase */
711 pDrvIns->IBase.pfnQueryInterface = drvNATQueryInterface;
712 /* INetwork */
713 pThis->INetworkConnector.pfnSend = drvNATSend;
714 pThis->INetworkConnector.pfnSetPromiscuousMode = drvNATSetPromiscuousMode;
715 pThis->INetworkConnector.pfnNotifyLinkChanged = drvNATNotifyLinkChanged;
716
717 /*
718 * Get the configuration settings.
719 */
720 bool fPassDomain = true;
721 int rc = CFGMR3QueryBool(pCfgHandle, "PassDomain", &fPassDomain);
722 if (rc == VERR_CFGM_VALUE_NOT_FOUND)
723 fPassDomain = true;
724 else if (RT_FAILURE(rc))
725 return PDMDrvHlpVMSetError(pDrvIns, rc, RT_SRC_POS, N_("NAT#%d: configuration query for \"PassDomain\" boolean failed"), pDrvIns->iInstance);
726
727 rc = CFGMR3QueryStringAlloc(pCfgHandle, "TFTPPrefix", &pThis->pszTFTPPrefix);
728 if (RT_FAILURE(rc) && rc != VERR_CFGM_VALUE_NOT_FOUND)
729 return PDMDrvHlpVMSetError(pDrvIns, rc, RT_SRC_POS, N_("NAT#%d: configuration query for \"TFTPPrefix\" string failed"), pDrvIns->iInstance);
730 rc = CFGMR3QueryStringAlloc(pCfgHandle, "BootFile", &pThis->pszBootFile);
731 if (RT_FAILURE(rc) && rc != VERR_CFGM_VALUE_NOT_FOUND)
732 return PDMDrvHlpVMSetError(pDrvIns, rc, RT_SRC_POS, N_("NAT#%d: configuration query for \"BootFile\" string failed"), pDrvIns->iInstance);
733
734 /*
735 * Query the network port interface.
736 */
737 pThis->pPort = (PPDMINETWORKPORT)pDrvIns->pUpBase->pfnQueryInterface(pDrvIns->pUpBase, PDMINTERFACE_NETWORK_PORT);
738 if (!pThis->pPort)
739 return PDMDRV_SET_ERROR(pDrvIns, VERR_PDM_MISSING_INTERFACE_ABOVE,
740 N_("Configuration error: the above device/driver didn't export the network port interface"));
741 pThis->pConfig = (PPDMINETWORKCONFIG)pDrvIns->pUpBase->pfnQueryInterface(pDrvIns->pUpBase, PDMINTERFACE_NETWORK_CONFIG);
742 if (!pThis->pConfig)
743 return PDMDRV_SET_ERROR(pDrvIns, VERR_PDM_MISSING_INTERFACE_ABOVE,
744 N_("Configuration error: the above device/driver didn't export the network config interface"));
745
746 /* Generate a network address for this network card. */
747 rc = CFGMR3QueryString(pCfgHandle, "Network", szNetwork, sizeof(szNetwork));
748 if (rc == VERR_CFGM_VALUE_NOT_FOUND)
749 RTStrPrintf(szNetwork, sizeof(szNetwork), "10.0.%d.0/24", pDrvIns->iInstance + 2);
750 else if (RT_FAILURE(rc))
751 return PDMDrvHlpVMSetError(pDrvIns, rc, RT_SRC_POS, N_("NAT#%d: configuration query for \"Network\" string failed"), pDrvIns->iInstance);
752
753 RTIPV4ADDR Network;
754 RTIPV4ADDR Netmask;
755 rc = RTCidrStrToIPv4(szNetwork, &Network, &Netmask);
756 if (RT_FAILURE(rc))
757 return PDMDrvHlpVMSetError(pDrvIns, rc, RT_SRC_POS, N_("NAT#%d: Configuration error: network '%s' describes not a valid IPv4 network"), pDrvIns->iInstance, szNetwork);
758
759 RTStrPrintf(szNetAddr, sizeof(szNetAddr), "%d.%d.%d.%d",
760 (Network & 0xFF000000) >> 24, (Network & 0xFF0000) >> 16, (Network & 0xFF00) >> 8, Network & 0xFF);
761
762 /*
763 * The slirp lock..
764 */
765#ifndef VBOX_WITH_SIMPLIFIED_SLIRP_SYNC
766 rc = RTCritSectInit(&pThis->CritSect);
767 if (RT_FAILURE(rc))
768 return rc;
769#endif
770 /*
771 * Initialize slirp.
772 */
773 rc = slirp_init(&pThis->pNATState, &szNetAddr[0], Netmask, fPassDomain, pThis->pszTFTPPrefix, pThis->pszBootFile, pThis);
774 if (RT_SUCCESS(rc))
775 {
776 slirp_register_timers(pThis->pNATState, pDrvIns);
777 int rc2 = drvNATConstructRedir(pDrvIns->iInstance, pThis, pCfgHandle, Network);
778 if (RT_SUCCESS(rc2))
779 {
780 /*
781 * Register a load done notification to get the MAC address into the slirp
782 * engine after we loaded a guest state.
783 */
784 rc2 = PDMDrvHlpSSMRegister(pDrvIns, pDrvIns->pDrvReg->szDriverName,
785 pDrvIns->iInstance, 0, 0,
786 NULL, NULL, NULL, NULL, NULL, drvNATLoadDone);
787 AssertRC(rc2);
788#ifndef VBOX_WITH_SIMPLIFIED_SLIRP_SYNC
789 pDrvIns->pDrvHlp->pfnPDMPollerRegister(pDrvIns, drvNATPoller);
790#else
791 rc = RTReqCreateQueue(&pThis->pReqQueue);
792 if (RT_FAILURE(rc)) {
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 LogRel(("Can't create send queue\n"));
800 return rc;
801 }
802
803# ifndef RT_OS_WINDOWS
804 /*
805 * Create the control pipe.
806 */
807 int fds[2];
808 if (pipe(&fds[0]) != 0) /** @todo RTPipeCreate() or something... */
809 {
810 int rc = RTErrConvertFromErrno(errno);
811 AssertRC(rc);
812 return rc;
813 }
814 pThis->PipeRead = fds[0];
815 pThis->PipeWrite = fds[1];
816# else
817 pThis->hWakeupEvent = CreateEvent(NULL, FALSE, FALSE, NULL); /* auto-reset event */
818 slirp_register_external_event(pThis->pNATState, pThis->hWakeupEvent, VBOX_WAKEUP_EVENT_INDEX);
819# endif
820
821 rc = PDMDrvHlpPDMThreadCreate(pDrvIns, &pThis->pThread, pThis, drvNATAsyncIoThread, drvNATAsyncIoWakeup, 128 * _1K, RTTHREADTYPE_IO, "NAT");
822 AssertReleaseRC(rc);
823#endif
824
825 pThis->enmLinkState = PDMNETWORKLINKSTATE_UP;
826
827 /* might return VINF_NAT_DNS */
828 return rc;
829 }
830 /* failure path */
831 rc = rc2;
832 slirp_term(pThis->pNATState);
833 pThis->pNATState = NULL;
834 }
835 else
836 {
837 PDMDRV_SET_ERROR(pDrvIns, rc, N_("Unknown error during NAT networking setup: "));
838 AssertMsgFailed(("Add error message for rc=%d (%Rrc)\n", rc, rc));
839 }
840
841#ifndef VBOX_WITH_SIMPLIFIED_SLIRP_SYNC
842 RTCritSectDelete(&pThis->CritSect);
843#endif
844 return rc;
845}
846
847
848/**
849 * NAT network transport driver registration record.
850 */
851const PDMDRVREG g_DrvNAT =
852{
853 /* u32Version */
854 PDM_DRVREG_VERSION,
855 /* szDriverName */
856 "NAT",
857 /* pszDescription */
858 "NAT Network Transport Driver",
859 /* fFlags */
860 PDM_DRVREG_FLAGS_HOST_BITS_DEFAULT,
861 /* fClass. */
862 PDM_DRVREG_CLASS_NETWORK,
863 /* cMaxInstances */
864 16,
865 /* cbInstance */
866 sizeof(DRVNAT),
867 /* pfnConstruct */
868 drvNATConstruct,
869 /* pfnDestruct */
870 drvNATDestruct,
871 /* pfnIOCtl */
872 NULL,
873 /* pfnPowerOn */
874 drvNATPowerOn,
875 /* pfnReset */
876 NULL,
877 /* pfnSuspend */
878 NULL,
879 /* pfnResume */
880 NULL,
881 /* pfnDetach */
882 NULL,
883 /* pfnPowerOff */
884 NULL
885};
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