VirtualBox

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

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

slirp: simplified sync is default now

  • Property svn:eol-style set to native
  • Property svn:keywords set to Author Date Id Revision
File size: 27.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/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_SIMPLIFIED_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_SIMPLIFIED_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_SIMPLIFIED_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_SIMPLIFIED_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_SIMPLIFIED_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_SIMPLIFIED_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_SIMPLIFIED_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_SIMPLIFIED_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_SIMPLIFIED_SLIRP_SYNC */
272}
273
274
275#ifndef VBOX_WITH_SIMPLIFIED_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_SIMPLIFIED_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 unsigned int ms;
314# ifdef RT_OS_WINDOWS
315 DWORD event;
316 HANDLE *phEvents;
317# endif
318
319 LogFlow(("drvNATAsyncIoThread: pThis=%p\n", pThis));
320
321 if (pThread->enmState == PDMTHREADSTATE_INITIALIZING)
322 return VINF_SUCCESS;
323
324#ifdef RT_OS_WINDOWS
325 phEvents = slirp_get_events(pThis->pNATState);
326#endif
327
328 /*
329 * Polling loop.
330 */
331 while (pThread->enmState == PDMTHREADSTATE_RUNNING)
332 {
333 FD_ZERO(&ReadFDs);
334 FD_ZERO(&WriteFDs);
335 FD_ZERO(&XcptFDs);
336 nFDs = -1;
337
338 /*
339 * To prevent concurent execution of sending/receving threads
340 */
341 slirp_select_fill(pThis->pNATState, &nFDs, &ReadFDs, &WriteFDs, &XcptFDs);
342 ms = slirp_get_timeout_ms(pThis->pNATState);
343# ifndef RT_OS_WINDOWS
344 struct timeval tv = { 0, ms*1000 };
345 FD_SET(pThis->PipeRead, &ReadFDs);
346 nFDs = ((int)pThis->PipeRead < nFDs ? nFDs : pThis->PipeRead);
347 int cChangedFDs = select(nFDs + 1, &ReadFDs, &WriteFDs, &XcptFDs, ms ? &tv : NULL);
348 if (cChangedFDs >= 0)
349 {
350 slirp_select_poll(pThis->pNATState, &ReadFDs, &WriteFDs, &XcptFDs);
351 if (FD_ISSET(pThis->PipeRead, &ReadFDs))
352 {
353 /* drain the pipe */
354 char ch[1];
355 size_t cbRead;
356 RTFileRead(pThis->PipeRead, &ch, 1, &cbRead);
357 }
358 /* process _all_ outstanding requests but don't wait */
359 RTReqProcess(pThis->pReqQueue, 0);
360 }
361# else /* RT_OS_WINDOWS */
362 event = WSAWaitForMultipleEvents(nFDs, phEvents, FALSE, ms ? ms : WSA_INFINITE, FALSE);
363 if ( (event < WSA_WAIT_EVENT_0 || event > WSA_WAIT_EVENT_0 + nFDs - 1)
364 && event != WSA_WAIT_TIMEOUT)
365 {
366 int error = WSAGetLastError();
367 LogRel(("WSAWaitForMultipleEvents returned %d (error %d)\n", event, error));
368 RTAssertReleasePanic();
369 }
370
371 if (event == WSA_WAIT_TIMEOUT)
372 {
373 /* only check for slow/fast timers */
374 slirp_select_poll(pThis->pNATState, NULL, NULL, NULL);
375 continue;
376 }
377
378 /* poll the sockets in any case */
379 slirp_select_poll(pThis->pNATState, &ReadFDs, &WriteFDs, &XcptFDs);
380 /* process _all_ outstanding requests but don't wait */
381 RTReqProcess(pThis->pReqQueue, 0);
382# endif /* RT_OS_WINDOWS */
383 }
384
385 return VINF_SUCCESS;
386}
387
388 /**
389 * Unblock the send thread so it can respond to a state change.
390 *
391 * @returns VBox status code.
392 * @param pDevIns The pcnet device instance.
393 * @param pThread The send thread.
394 */
395static DECLCALLBACK(int) drvNATAsyncIoWakeup(PPDMDRVINS pDrvIns, PPDMTHREAD pThread)
396{
397 PDRVNAT pThis = PDMINS_2_DATA(pDrvIns, PDRVNAT);
398
399# ifndef RT_OS_WINDOWS
400 /* kick select() */
401 int rc = RTFileWrite(pThis->PipeWrite, "", 1, NULL);
402 AssertRC(rc);
403# else
404 /* kick WSAWaitForMultipleEvents() */
405 WSASetEvent(pThis->hWakeupEvent);
406# endif
407
408 return VINF_SUCCESS;
409}
410
411#endif /* VBOX_WITH_SIMPLIFIED_SLIRP_SYNC */
412
413
414/**
415 * Function called by slirp to check if it's possible to feed incoming data to the network port.
416 * @returns 1 if possible.
417 * @returns 0 if not possible.
418 */
419int slirp_can_output(void *pvUser)
420{
421 PDRVNAT pThis = (PDRVNAT)pvUser;
422
423 Assert(pThis);
424
425#ifndef VBOX_WITH_SIMPLIFIED_SLIRP_SYNC
426 /** Happens during termination */
427 if (!RTCritSectIsOwner(&pThis->CritSect))
428 return 0;
429#endif
430
431 int rc = pThis->pPort->pfnWaitReceiveAvail(pThis->pPort, 0);
432 return RT_SUCCESS(rc);
433}
434
435
436/**
437 * Function called by slirp to feed incoming data to the network port.
438 */
439void slirp_output(void *pvUser, const uint8_t *pu8Buf, int cb)
440{
441 PDRVNAT pThis = (PDRVNAT)pvUser;
442
443 LogFlow(("slirp_output BEGIN %x %d\n", pu8Buf, cb));
444 Log2(("slirp_output: pu8Buf=%p cb=%#x (pThis=%p)\n%.*Rhxd\n", pu8Buf, cb, pThis, cb, pu8Buf));
445
446 Assert(pThis);
447
448#ifndef VBOX_WITH_SIMPLIFIED_SLIRP_SYNC
449 /** Happens during termination */
450 if (!RTCritSectIsOwner(&pThis->CritSect))
451 return;
452#endif
453
454 int rc = pThis->pPort->pfnReceive(pThis->pPort, pu8Buf, cb);
455 AssertRC(rc);
456 LogFlow(("slirp_output END %x %d\n", pu8Buf, cb));
457}
458
459/**
460 * Queries an interface to the driver.
461 *
462 * @returns Pointer to interface.
463 * @returns NULL if the interface was not supported by the driver.
464 * @param pInterface Pointer to this interface structure.
465 * @param enmInterface The requested interface identification.
466 * @thread Any thread.
467 */
468static DECLCALLBACK(void *) drvNATQueryInterface(PPDMIBASE pInterface, PDMINTERFACE enmInterface)
469{
470 PPDMDRVINS pDrvIns = PDMIBASE_2_PDMDRV(pInterface);
471 PDRVNAT pThis = PDMINS_2_DATA(pDrvIns, PDRVNAT);
472 switch (enmInterface)
473 {
474 case PDMINTERFACE_BASE:
475 return &pDrvIns->IBase;
476 case PDMINTERFACE_NETWORK_CONNECTOR:
477 return &pThis->INetworkConnector;
478 default:
479 return NULL;
480 }
481}
482
483
484/**
485 * Destruct a driver instance.
486 *
487 * Most VM resources are freed by the VM. This callback is provided so that any non-VM
488 * resources can be freed correctly.
489 *
490 * @param pDrvIns The driver instance data.
491 */
492static DECLCALLBACK(void) drvNATDestruct(PPDMDRVINS pDrvIns)
493{
494 PDRVNAT pThis = PDMINS_2_DATA(pDrvIns, PDRVNAT);
495
496 LogFlow(("drvNATDestruct:\n"));
497
498#ifndef VBOX_WITH_SIMPLIFIED_SLIRP_SYNC
499 int rc = RTCritSectEnter(&pThis->CritSect);
500 AssertReleaseRC(rc);
501#endif
502 slirp_term(pThis->pNATState);
503 pThis->pNATState = NULL;
504#ifndef VBOX_WITH_SIMPLIFIED_SLIRP_SYNC
505 RTCritSectLeave(&pThis->CritSect);
506 RTCritSectDelete(&pThis->CritSect);
507#endif
508}
509
510
511/**
512 * Sets up the redirectors.
513 *
514 * @returns VBox status code.
515 * @param pCfgHandle The drivers configuration handle.
516 */
517static int drvNATConstructRedir(unsigned iInstance, PDRVNAT pThis, PCFGMNODE pCfgHandle, RTIPV4ADDR Network)
518{
519 /*
520 * Enumerate redirections.
521 */
522 for (PCFGMNODE pNode = CFGMR3GetFirstChild(pCfgHandle); pNode; pNode = CFGMR3GetNextChild(pNode))
523 {
524 /*
525 * Validate the port forwarding config.
526 */
527 if (!CFGMR3AreValuesValid(pNode, "Protocol\0UDP\0HostPort\0GuestPort\0GuestIP\0"))
528 return PDMDRV_SET_ERROR(pThis->pDrvIns, VERR_PDM_DRVINS_UNKNOWN_CFG_VALUES, N_("Unknown configuration in port forwarding"));
529
530 /* protocol type */
531 bool fUDP;
532 char szProtocol[32];
533 int rc = CFGMR3QueryString(pNode, "Protocol", &szProtocol[0], sizeof(szProtocol));
534 if (rc == VERR_CFGM_VALUE_NOT_FOUND)
535 {
536 rc = CFGMR3QueryBool(pNode, "UDP", &fUDP);
537 if (rc == VERR_CFGM_VALUE_NOT_FOUND)
538 fUDP = false;
539 else if (RT_FAILURE(rc))
540 return PDMDrvHlpVMSetError(pThis->pDrvIns, rc, RT_SRC_POS, N_("NAT#%d: configuration query for \"UDP\" boolean failed"), iInstance);
541 }
542 else if (RT_SUCCESS(rc))
543 {
544 if (!RTStrICmp(szProtocol, "TCP"))
545 fUDP = false;
546 else if (!RTStrICmp(szProtocol, "UDP"))
547 fUDP = true;
548 else
549 return PDMDrvHlpVMSetError(pThis->pDrvIns, VERR_INVALID_PARAMETER, RT_SRC_POS, N_("NAT#%d: Invalid configuration value for \"Protocol\": \"%s\""), iInstance, szProtocol);
550 }
551 else
552 return PDMDrvHlpVMSetError(pThis->pDrvIns, rc, RT_SRC_POS, N_("NAT#%d: configuration query for \"Protocol\" string failed"), iInstance);
553
554 /* host port */
555 int32_t iHostPort;
556 rc = CFGMR3QueryS32(pNode, "HostPort", &iHostPort);
557 if (RT_FAILURE(rc))
558 return PDMDrvHlpVMSetError(pThis->pDrvIns, rc, RT_SRC_POS, N_("NAT#%d: configuration query for \"HostPort\" integer failed"), iInstance);
559
560 /* guest port */
561 int32_t iGuestPort;
562 rc = CFGMR3QueryS32(pNode, "GuestPort", &iGuestPort);
563 if (RT_FAILURE(rc))
564 return PDMDrvHlpVMSetError(pThis->pDrvIns, rc, RT_SRC_POS, N_("NAT#%d: configuration query for \"GuestPort\" integer failed"), iInstance);
565
566 /* guest address */
567 char szGuestIP[32];
568 rc = CFGMR3QueryString(pNode, "GuestIP", &szGuestIP[0], sizeof(szGuestIP));
569 if (rc == VERR_CFGM_VALUE_NOT_FOUND)
570 RTStrPrintf(szGuestIP, sizeof(szGuestIP), "%d.%d.%d.%d",
571 (Network & 0xFF000000) >> 24, (Network & 0xFF0000) >> 16, (Network & 0xFF00) >> 8, (Network & 0xE0) | 15);
572 else if (RT_FAILURE(rc))
573 return PDMDrvHlpVMSetError(pThis->pDrvIns, rc, RT_SRC_POS, N_("NAT#%d: configuration query for \"GuestIP\" string failed"), iInstance);
574 struct in_addr GuestIP;
575 if (!inet_aton(szGuestIP, &GuestIP))
576 return PDMDrvHlpVMSetError(pThis->pDrvIns, VERR_NAT_REDIR_GUEST_IP, RT_SRC_POS,
577 N_("NAT#%d: configuration error: invalid \"GuestIP\"=\"%s\", inet_aton failed"), iInstance, szGuestIP);
578
579 /*
580 * Call slirp about it.
581 */
582 Log(("drvNATConstruct: Redir %d -> %s:%d\n", iHostPort, szGuestIP, iGuestPort));
583 if (slirp_redir(pThis->pNATState, fUDP, iHostPort, GuestIP, iGuestPort) < 0)
584 return PDMDrvHlpVMSetError(pThis->pDrvIns, VERR_NAT_REDIR_SETUP, RT_SRC_POS,
585 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);
586 } /* for each redir rule */
587
588 return VINF_SUCCESS;
589}
590
591/**
592 * Get the MAC address into the slirp stack.
593 */
594static void drvNATSetMac(PDRVNAT pThis)
595{
596 if (pThis->pConfig)
597 {
598 RTMAC Mac;
599 pThis->pConfig->pfnGetMac(pThis->pConfig, &Mac);
600 slirp_set_ethaddr(pThis->pNATState, Mac.au8);
601 }
602}
603
604
605/**
606 * After loading we have to pass the MAC address of the ethernet device to the slirp stack.
607 * Otherwise the guest is not reachable until it performs a DHCP request or an ARP request
608 * (usually done during guest boot).
609 */
610static DECLCALLBACK(int) drvNATLoadDone(PPDMDRVINS pDrvIns, PSSMHANDLE pSSMHandle)
611{
612 PDRVNAT pThis = PDMINS_2_DATA(pDrvIns, PDRVNAT);
613 drvNATSetMac(pThis);
614 return VINF_SUCCESS;
615}
616
617
618/**
619 * Some guests might not use DHCP to retrieve an IP but use a static IP.
620 */
621static DECLCALLBACK(void) drvNATPowerOn(PPDMDRVINS pDrvIns)
622{
623 PDRVNAT pThis = PDMINS_2_DATA(pDrvIns, PDRVNAT);
624 drvNATSetMac(pThis);
625}
626
627
628/**
629 * Construct a NAT network transport driver instance.
630 *
631 * @returns VBox status.
632 * @param pDrvIns The driver instance data.
633 * If the registration structure is needed, pDrvIns->pDrvReg points to it.
634 * @param pCfgHandle Configuration node handle for the driver. Use this to obtain the configuration
635 * of the driver instance. It's also found in pDrvIns->pCfgHandle, but like
636 * iInstance it's expected to be used a bit in this function.
637 */
638static DECLCALLBACK(int) drvNATConstruct(PPDMDRVINS pDrvIns, PCFGMNODE pCfgHandle)
639{
640 PDRVNAT pThis = PDMINS_2_DATA(pDrvIns, PDRVNAT);
641 char szNetAddr[16];
642 char szNetwork[32]; /* xxx.xxx.xxx.xxx/yy */
643 LogFlow(("drvNATConstruct:\n"));
644
645 /*
646 * Validate the config.
647 */
648 if (!CFGMR3AreValuesValid(pCfgHandle, "PassDomain\0TFTPPrefix\0BootFile\0Network\0"))
649 return PDMDRV_SET_ERROR(pDrvIns, VERR_PDM_DRVINS_UNKNOWN_CFG_VALUES, N_("Unknown NAT configuration option, only supports PassDomain, TFTPPrefix, BootFile and Network"));
650
651 /*
652 * Init the static parts.
653 */
654 pThis->pDrvIns = pDrvIns;
655 pThis->pNATState = NULL;
656 pThis->pszTFTPPrefix = NULL;
657 pThis->pszBootFile = NULL;
658 /* IBase */
659 pDrvIns->IBase.pfnQueryInterface = drvNATQueryInterface;
660 /* INetwork */
661 pThis->INetworkConnector.pfnSend = drvNATSend;
662 pThis->INetworkConnector.pfnSetPromiscuousMode = drvNATSetPromiscuousMode;
663 pThis->INetworkConnector.pfnNotifyLinkChanged = drvNATNotifyLinkChanged;
664
665 /*
666 * Get the configuration settings.
667 */
668 bool fPassDomain = true;
669 int rc = CFGMR3QueryBool(pCfgHandle, "PassDomain", &fPassDomain);
670 if (rc == VERR_CFGM_VALUE_NOT_FOUND)
671 fPassDomain = true;
672 else if (RT_FAILURE(rc))
673 return PDMDrvHlpVMSetError(pDrvIns, rc, RT_SRC_POS, N_("NAT#%d: configuration query for \"PassDomain\" boolean failed"), pDrvIns->iInstance);
674
675 rc = CFGMR3QueryStringAlloc(pCfgHandle, "TFTPPrefix", &pThis->pszTFTPPrefix);
676 if (RT_FAILURE(rc) && rc != VERR_CFGM_VALUE_NOT_FOUND)
677 return PDMDrvHlpVMSetError(pDrvIns, rc, RT_SRC_POS, N_("NAT#%d: configuration query for \"TFTPPrefix\" string failed"), pDrvIns->iInstance);
678 rc = CFGMR3QueryStringAlloc(pCfgHandle, "BootFile", &pThis->pszBootFile);
679 if (RT_FAILURE(rc) && rc != VERR_CFGM_VALUE_NOT_FOUND)
680 return PDMDrvHlpVMSetError(pDrvIns, rc, RT_SRC_POS, N_("NAT#%d: configuration query for \"BootFile\" string failed"), pDrvIns->iInstance);
681
682 /*
683 * Query the network port interface.
684 */
685 pThis->pPort = (PPDMINETWORKPORT)pDrvIns->pUpBase->pfnQueryInterface(pDrvIns->pUpBase, PDMINTERFACE_NETWORK_PORT);
686 if (!pThis->pPort)
687 return PDMDRV_SET_ERROR(pDrvIns, VERR_PDM_MISSING_INTERFACE_ABOVE,
688 N_("Configuration error: the above device/driver didn't export the network port interface"));
689 pThis->pConfig = (PPDMINETWORKCONFIG)pDrvIns->pUpBase->pfnQueryInterface(pDrvIns->pUpBase, PDMINTERFACE_NETWORK_CONFIG);
690 if (!pThis->pConfig)
691 return PDMDRV_SET_ERROR(pDrvIns, VERR_PDM_MISSING_INTERFACE_ABOVE,
692 N_("Configuration error: the above device/driver didn't export the network config interface"));
693
694 /* Generate a network address for this network card. */
695 rc = CFGMR3QueryString(pCfgHandle, "Network", szNetwork, sizeof(szNetwork));
696 if (rc == VERR_CFGM_VALUE_NOT_FOUND)
697 RTStrPrintf(szNetwork, sizeof(szNetwork), "10.0.%d.0/24", pDrvIns->iInstance + 2);
698 else if (RT_FAILURE(rc))
699 return PDMDrvHlpVMSetError(pDrvIns, rc, RT_SRC_POS, N_("NAT#%d: configuration query for \"Network\" string failed"), pDrvIns->iInstance);
700
701 RTIPV4ADDR Network;
702 RTIPV4ADDR Netmask;
703 rc = RTCidrStrToIPv4(szNetwork, &Network, &Netmask);
704 if (RT_FAILURE(rc))
705 return PDMDrvHlpVMSetError(pDrvIns, rc, RT_SRC_POS, N_("NAT#%d: Configuration error: network '%s' describes not a valid IPv4 network"), pDrvIns->iInstance, szNetwork);
706
707 RTStrPrintf(szNetAddr, sizeof(szNetAddr), "%d.%d.%d.%d",
708 (Network & 0xFF000000) >> 24, (Network & 0xFF0000) >> 16, (Network & 0xFF00) >> 8, Network & 0xFF);
709
710 /*
711 * The slirp lock..
712 */
713#ifndef VBOX_WITH_SIMPLIFIED_SLIRP_SYNC
714 rc = RTCritSectInit(&pThis->CritSect);
715 if (RT_FAILURE(rc))
716 return rc;
717#endif
718 /*
719 * Initialize slirp.
720 */
721 rc = slirp_init(&pThis->pNATState, &szNetAddr[0], Netmask, fPassDomain, pThis->pszTFTPPrefix, pThis->pszBootFile, pThis);
722 if (RT_SUCCESS(rc))
723 {
724 slirp_register_timers(pThis->pNATState, pDrvIns);
725 int rc2 = drvNATConstructRedir(pDrvIns->iInstance, pThis, pCfgHandle, Network);
726 if (RT_SUCCESS(rc2))
727 {
728 /*
729 * Register a load done notification to get the MAC address into the slirp
730 * engine after we loaded a guest state.
731 */
732 rc2 = PDMDrvHlpSSMRegister(pDrvIns, pDrvIns->pDrvReg->szDriverName,
733 pDrvIns->iInstance, 0, 0,
734 NULL, NULL, NULL, NULL, NULL, drvNATLoadDone);
735 AssertRC(rc2);
736#ifndef VBOX_WITH_SIMPLIFIED_SLIRP_SYNC
737 pDrvIns->pDrvHlp->pfnPDMPollerRegister(pDrvIns, drvNATPoller);
738#else
739 rc = RTReqCreateQueue(&pThis->pReqQueue);
740 if (RT_FAILURE(rc))
741 return rc;
742
743# ifndef RT_OS_WINDOWS
744 /*
745 * Create the control pipe.
746 */
747 int fds[2];
748 if (pipe(&fds[0]) != 0) /** @todo RTPipeCreate() or something... */
749 {
750 int rc = RTErrConvertFromErrno(errno);
751 AssertRC(rc);
752 return rc;
753 }
754 pThis->PipeRead = fds[0];
755 pThis->PipeWrite = fds[1];
756# else
757 pThis->hWakeupEvent = CreateEvent(NULL, FALSE, FALSE, NULL); /* auto-reset event */
758 slirp_register_external_event(pThis->pNATState, pThis->hWakeupEvent, VBOX_WAKEUP_EVENT_INDEX);
759# endif
760
761 rc = PDMDrvHlpPDMThreadCreate(pDrvIns, &pThis->pThread, pThis, drvNATAsyncIoThread, drvNATAsyncIoWakeup, 128 * _1K, RTTHREADTYPE_IO, "NAT");
762 AssertReleaseRC(rc);
763#endif
764
765 pThis->enmLinkState = PDMNETWORKLINKSTATE_UP;
766
767 /* might return VINF_NAT_DNS */
768 return rc;
769 }
770 /* failure path */
771 rc = rc2;
772 slirp_term(pThis->pNATState);
773 pThis->pNATState = NULL;
774 }
775 else
776 {
777 PDMDRV_SET_ERROR(pDrvIns, rc, N_("Unknown error during NAT networking setup: "));
778 AssertMsgFailed(("Add error message for rc=%d (%Rrc)\n", rc, rc));
779 }
780
781#ifndef VBOX_WITH_SIMPLIFIED_SLIRP_SYNC
782 RTCritSectDelete(&pThis->CritSect);
783#endif
784 return rc;
785}
786
787
788/**
789 * NAT network transport driver registration record.
790 */
791const PDMDRVREG g_DrvNAT =
792{
793 /* u32Version */
794 PDM_DRVREG_VERSION,
795 /* szDriverName */
796 "NAT",
797 /* pszDescription */
798 "NAT Network Transport Driver",
799 /* fFlags */
800 PDM_DRVREG_FLAGS_HOST_BITS_DEFAULT,
801 /* fClass. */
802 PDM_DRVREG_CLASS_NETWORK,
803 /* cMaxInstances */
804 16,
805 /* cbInstance */
806 sizeof(DRVNAT),
807 /* pfnConstruct */
808 drvNATConstruct,
809 /* pfnDestruct */
810 drvNATDestruct,
811 /* pfnIOCtl */
812 NULL,
813 /* pfnPowerOn */
814 drvNATPowerOn,
815 /* pfnReset */
816 NULL,
817 /* pfnSuspend */
818 NULL,
819 /* pfnResume */
820 NULL,
821 /* pfnDetach */
822 NULL,
823 /* pfnPowerOff */
824 NULL
825};
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