VirtualBox

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

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

no need to loop here, this is already done in the function

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