VirtualBox

source: vbox/trunk/src/VBox/Main/src-server/NATNetworkImpl.cpp@ 93115

Last change on this file since 93115 was 93115, checked in by vboxsync, 3 years ago

scm --update-copyright-year

  • Property svn:eol-style set to native
  • Property svn:keywords set to Author Date Id Revision
File size: 37.6 KB
Line 
1/* $Id: NATNetworkImpl.cpp 93115 2022-01-01 11:31:46Z vboxsync $ */
2/** @file
3 * INATNetwork implementation.
4 */
5
6/*
7 * Copyright (C) 2013-2022 Oracle Corporation
8 *
9 * This file is part of VirtualBox Open Source Edition (OSE), as
10 * available from http://www.virtualbox.org. This file is free software;
11 * you can redistribute it and/or modify it under the terms of the GNU
12 * General Public License (GPL) as published by the Free Software
13 * Foundation, in version 2 as it comes in the "COPYING" file of the
14 * VirtualBox OSE distribution. VirtualBox OSE is distributed in the
15 * hope that it will be useful, but WITHOUT ANY WARRANTY of any kind.
16 */
17
18#define LOG_GROUP LOG_GROUP_MAIN_NATNETWORK
19#include "NetworkServiceRunner.h"
20#include "DHCPServerImpl.h"
21#include "NATNetworkImpl.h"
22#include "AutoCaller.h"
23
24#include <iprt/asm.h>
25#include <iprt/cpp/utils.h>
26#include <iprt/net.h>
27#include <iprt/cidr.h>
28#include <iprt/net.h>
29#include <VBox/com/array.h>
30#include <VBox/com/ptr.h>
31#include <VBox/settings.h>
32
33#include "EventImpl.h"
34#include "LoggingNew.h"
35
36#include "VirtualBoxImpl.h"
37#include <algorithm>
38#include <list>
39
40#ifndef RT_OS_WINDOWS
41# include <netinet/in.h>
42#else
43# define IN_LOOPBACKNET 127
44#endif
45
46
47// constructor / destructor
48/////////////////////////////////////////////////////////////////////////////
49struct NATNetwork::Data
50{
51 Data()
52 : pVirtualBox(NULL)
53 , offGateway(0)
54 , offDhcp(0)
55 {
56 }
57 virtual ~Data(){}
58 const ComObjPtr<EventSource> pEventSource;
59#ifdef VBOX_WITH_NAT_SERVICE
60 NATNetworkServiceRunner NATRunner;
61 ComObjPtr<IDHCPServer> dhcpServer;
62#endif
63 /** weak VirtualBox parent */
64 VirtualBox * const pVirtualBox;
65
66 /** NATNetwork settings */
67 settings::NATNetwork s;
68
69 com::Utf8Str IPv4Gateway;
70 com::Utf8Str IPv4NetworkMask;
71 com::Utf8Str IPv4DhcpServer;
72 com::Utf8Str IPv4DhcpServerLowerIp;
73 com::Utf8Str IPv4DhcpServerUpperIp;
74
75 uint32_t offGateway;
76 uint32_t offDhcp;
77
78 void recalculatePortForwarding(const RTNETADDRIPV4 &AddrNew, const RTNETADDRIPV4 &MaskNew);
79};
80
81
82NATNetwork::NATNetwork()
83 : m(NULL)
84{
85}
86
87
88NATNetwork::~NATNetwork()
89{
90}
91
92
93HRESULT NATNetwork::FinalConstruct()
94{
95 return BaseFinalConstruct();
96}
97
98
99void NATNetwork::FinalRelease()
100{
101 uninit();
102
103 BaseFinalRelease();
104}
105
106
107void NATNetwork::uninit()
108{
109 /* Enclose the state transition Ready->InUninit->NotReady */
110 AutoUninitSpan autoUninitSpan(this);
111 if (autoUninitSpan.uninitDone())
112 return;
113 unconst(m->pVirtualBox) = NULL;
114 delete m;
115 m = NULL;
116}
117
118HRESULT NATNetwork::init(VirtualBox *aVirtualBox, com::Utf8Str aName)
119{
120 AutoInitSpan autoInitSpan(this);
121 AssertReturn(autoInitSpan.isOk(), E_FAIL);
122
123 m = new Data();
124 /* share VirtualBox weakly */
125 unconst(m->pVirtualBox) = aVirtualBox;
126 m->s.strNetworkName = aName;
127 m->s.strIPv4NetworkCidr = "10.0.2.0/24";
128 m->offGateway = 1;
129 i_recalculateIPv6Prefix(); /* set m->strIPv6Prefix based on IPv4 */
130
131 settings::NATHostLoopbackOffset off;
132 off.strLoopbackHostAddress = "127.0.0.1";
133 off.u32Offset = (uint32_t)2;
134 m->s.llHostLoopbackOffsetList.push_back(off);
135
136 i_recalculateIpv4AddressAssignments();
137
138 HRESULT hrc = unconst(m->pEventSource).createObject();
139 if (FAILED(hrc)) throw hrc;
140
141 hrc = m->pEventSource->init();
142 if (FAILED(hrc)) throw hrc;
143
144 /* Confirm a successful initialization */
145 autoInitSpan.setSucceeded();
146
147 return S_OK;
148}
149
150
151HRESULT NATNetwork::setErrorBusy()
152{
153 return setError(E_FAIL,
154 tr("Unable to change settings"
155 " while NATNetwork instance is running"));
156}
157
158
159HRESULT NATNetwork::i_loadSettings(const settings::NATNetwork &data)
160{
161 AutoCaller autoCaller(this);
162 AssertComRCReturnRC(autoCaller.rc());
163
164 AutoWriteLock alock(this COMMA_LOCKVAL_SRC_POS);
165 m->s = data;
166 if ( m->s.strIPv6Prefix.isEmpty()
167 /* also clean up bogus old default */
168 || m->s.strIPv6Prefix == "fe80::/64")
169 i_recalculateIPv6Prefix(); /* set m->strIPv6Prefix based on IPv4 */
170 i_recalculateIpv4AddressAssignments();
171
172 return S_OK;
173}
174
175HRESULT NATNetwork::i_saveSettings(settings::NATNetwork &data)
176{
177 AutoCaller autoCaller(this);
178 if (FAILED(autoCaller.rc())) return autoCaller.rc();
179
180 AutoReadLock alock(this COMMA_LOCKVAL_SRC_POS);
181 AssertReturn(!m->s.strNetworkName.isEmpty(), E_FAIL);
182 data = m->s;
183
184 m->pVirtualBox->i_onNATNetworkSetting(m->s.strNetworkName,
185 m->s.fEnabled,
186 m->s.strIPv4NetworkCidr,
187 m->IPv4Gateway,
188 m->s.fAdvertiseDefaultIPv6Route,
189 m->s.fNeedDhcpServer);
190
191 /* Notify listeners listening on this network only */
192 ::FireNATNetworkSettingEvent(m->pEventSource,
193 m->s.strNetworkName,
194 m->s.fEnabled,
195 m->s.strIPv4NetworkCidr,
196 m->IPv4Gateway,
197 m->s.fAdvertiseDefaultIPv6Route,
198 m->s.fNeedDhcpServer);
199
200 return S_OK;
201}
202
203HRESULT NATNetwork::getEventSource(ComPtr<IEventSource> &aEventSource)
204{
205 /* event source is const, no need to lock */
206 m->pEventSource.queryInterfaceTo(aEventSource.asOutParam());
207 return S_OK;
208}
209
210HRESULT NATNetwork::getNetworkName(com::Utf8Str &aNetworkName)
211{
212 AssertReturn(!m->s.strNetworkName.isEmpty(), E_FAIL);
213 aNetworkName = m->s.strNetworkName;
214 return S_OK;
215}
216
217HRESULT NATNetwork::setNetworkName(const com::Utf8Str &aNetworkName)
218{
219 if (aNetworkName.isEmpty())
220 return setError(E_INVALIDARG,
221 tr("Network name cannot be empty"));
222
223 {
224 AutoReadLock alockNatNetList(m->pVirtualBox->i_getNatNetLock() COMMA_LOCKVAL_SRC_POS);
225 if (m->pVirtualBox->i_isNatNetStarted(m->s.strNetworkName))
226 return setErrorBusy();
227
228 /** @todo r=uwe who ensures there's no other network with that name? */
229
230 AutoWriteLock alock(this COMMA_LOCKVAL_SRC_POS);
231 if (aNetworkName == m->s.strNetworkName)
232 return S_OK;
233
234 m->s.strNetworkName = aNetworkName;
235 }
236
237
238 AutoWriteLock vboxLock(m->pVirtualBox COMMA_LOCKVAL_SRC_POS);
239 HRESULT rc = m->pVirtualBox->i_saveSettings();
240 ComAssertComRCRetRC(rc);
241
242 return S_OK;
243}
244
245HRESULT NATNetwork::getEnabled(BOOL *aEnabled)
246{
247 *aEnabled = m->s.fEnabled;
248
249 i_recalculateIpv4AddressAssignments();
250 return S_OK;
251}
252
253HRESULT NATNetwork::setEnabled(const BOOL aEnabled)
254{
255 {
256 AutoWriteLock alock(this COMMA_LOCKVAL_SRC_POS);
257 if (RT_BOOL(aEnabled) == m->s.fEnabled)
258 return S_OK;
259 m->s.fEnabled = RT_BOOL(aEnabled);
260 }
261
262 AutoWriteLock vboxLock(m->pVirtualBox COMMA_LOCKVAL_SRC_POS);
263 HRESULT rc = m->pVirtualBox->i_saveSettings();
264 ComAssertComRCRetRC(rc);
265 return S_OK;
266}
267
268HRESULT NATNetwork::getGateway(com::Utf8Str &aIPv4Gateway)
269{
270 aIPv4Gateway = m->IPv4Gateway;
271 return S_OK;
272}
273
274HRESULT NATNetwork::getNetwork(com::Utf8Str &aNetwork)
275{
276 aNetwork = m->s.strIPv4NetworkCidr;
277 return S_OK;
278}
279
280
281HRESULT NATNetwork::setNetwork(const com::Utf8Str &aIPv4NetworkCidr)
282{
283 RTNETADDRIPV4 Net, Mask;
284 int iPrefix;
285 int rc;
286
287 rc = RTNetStrToIPv4Cidr(aIPv4NetworkCidr.c_str(), &Net, &iPrefix);
288 if (RT_FAILURE(rc))
289 return setError(E_FAIL, tr("%s is not a valid IPv4 CIDR notation"),
290 aIPv4NetworkCidr.c_str());
291
292 /*
293 * /32 is a single address, not a network, /31 is the degenerate
294 * point-to-point case, so reject these. Larger values and
295 * negative values are already treated as errors by the
296 * conversion.
297 */
298 if (iPrefix > 30)
299 return setError(E_FAIL, tr("%s network is too small"), aIPv4NetworkCidr.c_str());
300
301 if (iPrefix == 0)
302 return setError(E_FAIL, tr("%s specifies zero prefix"), aIPv4NetworkCidr.c_str());
303
304 rc = RTNetPrefixToMaskIPv4(iPrefix, &Mask);
305 AssertRCReturn(rc, setError(E_FAIL,
306 "%s: internal error: failed to convert prefix %d to netmask: %Rrc",
307 aIPv4NetworkCidr.c_str(), iPrefix, rc));
308
309 if ((Net.u & ~Mask.u) != 0)
310 return setError(E_FAIL,
311 tr("%s: the specified address is longer than the specified prefix"),
312 aIPv4NetworkCidr.c_str());
313
314 /** @todo r=uwe Check the address is unicast, not a loopback, etc. */
315
316 /* normalized CIDR notation */
317 com::Utf8StrFmt strCidr("%RTnaipv4/%d", Net.u, iPrefix);
318
319 {
320 AutoReadLock alockNatNetList(m->pVirtualBox->i_getNatNetLock() COMMA_LOCKVAL_SRC_POS);
321 if (m->pVirtualBox->i_isNatNetStarted(m->s.strNetworkName))
322 return setErrorBusy();
323
324 AutoWriteLock alock(this COMMA_LOCKVAL_SRC_POS);
325
326 if (m->s.strIPv4NetworkCidr == strCidr)
327 return S_OK;
328
329 m->recalculatePortForwarding(Net, Mask);
330
331 m->s.strIPv4NetworkCidr = strCidr;
332 i_recalculateIpv4AddressAssignments();
333 }
334
335 AutoWriteLock vboxLock(m->pVirtualBox COMMA_LOCKVAL_SRC_POS);
336 HRESULT hrc = m->pVirtualBox->i_saveSettings();
337 ComAssertComRCRetRC(hrc);
338 return S_OK;
339}
340
341
342/**
343 * Do best effort attempt at converting existing port forwarding rules
344 * from the old prefix to the new one. This might not be possible if
345 * the new prefix is longer (i.e. the network is smaller) or if a rule
346 * lists destination not from the network (though that rule wouldn't
347 * be terribly useful, at least currently).
348 */
349void NATNetwork::Data::recalculatePortForwarding(const RTNETADDRIPV4 &NetNew,
350 const RTNETADDRIPV4 &MaskNew)
351{
352 RTNETADDRIPV4 NetOld, MaskOld;
353 int iPrefixOld;
354 int rc;
355
356 if (s.mapPortForwardRules4.empty())
357 return; /* nothing to do */
358
359 rc = RTNetStrToIPv4Cidr(s.strIPv4NetworkCidr.c_str(), &NetOld, &iPrefixOld);
360 if (RT_FAILURE(rc))
361 return;
362
363 rc = RTNetPrefixToMaskIPv4(iPrefixOld, &MaskOld);
364 if (RT_FAILURE(rc))
365 return;
366
367 for (settings::NATRulesMap::iterator it = s.mapPortForwardRules4.begin();
368 it != s.mapPortForwardRules4.end();
369 ++it)
370 {
371 settings::NATRule &rule = it->second;
372
373 /* parse the old destination address */
374 RTNETADDRIPV4 AddrOld;
375 rc = RTNetStrToIPv4Addr(rule.strGuestIP.c_str(), &AddrOld);
376 if (RT_FAILURE(rc))
377 continue;
378
379 /* is it in the old network? (likely) */
380 if ((AddrOld.u & MaskOld.u) != NetOld.u)
381 continue;
382
383 uint32_t u32Host = (AddrOld.u & ~MaskOld.u);
384
385 /* does it fit into the new network? */
386 if ((u32Host & MaskNew.u) != 0)
387 continue;
388
389 rule.strGuestIP.printf("%RTnaipv4", NetNew.u | u32Host);
390 }
391}
392
393
394HRESULT NATNetwork::getIPv6Enabled(BOOL *aIPv6Enabled)
395{
396 *aIPv6Enabled = m->s.fIPv6Enabled;
397
398 return S_OK;
399}
400
401
402HRESULT NATNetwork::setIPv6Enabled(const BOOL aIPv6Enabled)
403{
404 {
405 AutoReadLock alockNatNetList(m->pVirtualBox->i_getNatNetLock() COMMA_LOCKVAL_SRC_POS);
406 if (m->pVirtualBox->i_isNatNetStarted(m->s.strNetworkName))
407 return setErrorBusy();
408
409 AutoWriteLock alock(this COMMA_LOCKVAL_SRC_POS);
410
411 if (RT_BOOL(aIPv6Enabled) == m->s.fIPv6Enabled)
412 return S_OK;
413
414 m->s.fIPv6Enabled = RT_BOOL(aIPv6Enabled);
415 }
416
417 AutoWriteLock vboxLock(m->pVirtualBox COMMA_LOCKVAL_SRC_POS);
418 HRESULT rc = m->pVirtualBox->i_saveSettings();
419 ComAssertComRCRetRC(rc);
420
421 return S_OK;
422}
423
424
425HRESULT NATNetwork::getIPv6Prefix(com::Utf8Str &aIPv6Prefix)
426{
427 AutoReadLock alock(this COMMA_LOCKVAL_SRC_POS);
428
429 aIPv6Prefix = m->s.strIPv6Prefix;
430 return S_OK;
431}
432
433HRESULT NATNetwork::setIPv6Prefix(const com::Utf8Str &aIPv6Prefix)
434{
435 HRESULT hrc;
436 int rc;
437
438 /* Since we store it in text form, use canonical representation */
439 com::Utf8Str strNormalizedIPv6Prefix;
440
441 const char *pcsz = RTStrStripL(aIPv6Prefix.c_str());
442 if (*pcsz != '\0') /* verify it first if not empty/blank */
443 {
444 RTNETADDRIPV6 Net6;
445 int iPrefixLength;
446 rc = RTNetStrToIPv6Cidr(aIPv6Prefix.c_str(), &Net6, &iPrefixLength);
447 if (RT_FAILURE(rc))
448 return setError(E_INVALIDARG,
449 tr("%s is not a valid IPv6 prefix"),
450 aIPv6Prefix.c_str());
451
452 /* Accept both addr:: and addr::/64 */
453 if (iPrefixLength == 128) /* no length was specified after the address? */
454 iPrefixLength = 64; /* take it to mean /64 which we require anyway */
455 else if (iPrefixLength != 64)
456 return setError(E_INVALIDARG,
457 tr("Invalid IPv6 prefix length %d, must be 64"),
458 iPrefixLength);
459
460 /* Verify the address is unicast. */
461 if ( ((Net6.au8[0] & 0xe0) != 0x20) /* global 2000::/3 */
462 && ((Net6.au8[0] & 0xfe) != 0xfc)) /* local fc00::/7 */
463 return setError(E_INVALIDARG,
464 tr("IPv6 prefix %RTnaipv6 is not unicast"),
465 &Net6);
466
467 /* Verify the interfaces ID part is zero */
468 if (Net6.au64[1] != 0)
469 return setError(E_INVALIDARG,
470 tr("Non-zero bits in the interface ID part"
471 " of the IPv6 prefix %RTnaipv6/64"),
472 &Net6);
473
474 rc = strNormalizedIPv6Prefix.printfNoThrow("%RTnaipv6/64", &Net6);
475 if (RT_FAILURE(rc))
476 {
477 if (rc == VERR_NO_MEMORY)
478 return setError(E_OUTOFMEMORY);
479 else
480 return setError(E_FAIL, tr("Internal error"));
481 }
482 }
483
484 {
485 AutoReadLock alockNatNetList(m->pVirtualBox->i_getNatNetLock() COMMA_LOCKVAL_SRC_POS);
486 if (m->pVirtualBox->i_isNatNetStarted(m->s.strNetworkName))
487 return setErrorBusy();
488
489 AutoWriteLock alock(this COMMA_LOCKVAL_SRC_POS);
490
491 if (strNormalizedIPv6Prefix == m->s.strIPv6Prefix)
492 return S_OK;
493
494 /* only allow prefix to be empty if IPv6 is disabled */
495 if (strNormalizedIPv6Prefix.isEmpty() && m->s.fIPv6Enabled)
496 return setError(E_FAIL, tr("Setting an empty IPv6 prefix when IPv6 is enabled"));
497
498 /**
499 * @todo
500 * silently ignore network IPv6 prefix update.
501 * todo: see similar todo in NATNetwork::COMSETTER(Network)(IN_BSTR)
502 */
503 if (!m->s.mapPortForwardRules6.empty())
504 return S_OK;
505
506 m->s.strIPv6Prefix = strNormalizedIPv6Prefix;
507 }
508
509 AutoWriteLock vboxLock(m->pVirtualBox COMMA_LOCKVAL_SRC_POS);
510 hrc = m->pVirtualBox->i_saveSettings();
511 ComAssertComRCRetRC(hrc);
512
513 return S_OK;
514}
515
516
517HRESULT NATNetwork::getAdvertiseDefaultIPv6RouteEnabled(BOOL *aAdvertiseDefaultIPv6Route)
518{
519 *aAdvertiseDefaultIPv6Route = m->s.fAdvertiseDefaultIPv6Route;
520
521 return S_OK;
522}
523
524
525HRESULT NATNetwork::setAdvertiseDefaultIPv6RouteEnabled(const BOOL aAdvertiseDefaultIPv6Route)
526{
527 {
528 AutoReadLock alockNatNetList(m->pVirtualBox->i_getNatNetLock() COMMA_LOCKVAL_SRC_POS);
529 if (m->pVirtualBox->i_isNatNetStarted(m->s.strNetworkName))
530 return setErrorBusy();
531
532 AutoWriteLock alock(this COMMA_LOCKVAL_SRC_POS);
533
534 if (RT_BOOL(aAdvertiseDefaultIPv6Route) == m->s.fAdvertiseDefaultIPv6Route)
535 return S_OK;
536
537 m->s.fAdvertiseDefaultIPv6Route = RT_BOOL(aAdvertiseDefaultIPv6Route);
538
539 }
540
541 AutoWriteLock vboxLock(m->pVirtualBox COMMA_LOCKVAL_SRC_POS);
542 HRESULT rc = m->pVirtualBox->i_saveSettings();
543 ComAssertComRCRetRC(rc);
544
545 return S_OK;
546}
547
548
549HRESULT NATNetwork::getNeedDhcpServer(BOOL *aNeedDhcpServer)
550{
551 *aNeedDhcpServer = m->s.fNeedDhcpServer;
552
553 return S_OK;
554}
555
556HRESULT NATNetwork::setNeedDhcpServer(const BOOL aNeedDhcpServer)
557{
558 {
559 AutoWriteLock alock(this COMMA_LOCKVAL_SRC_POS);
560
561 if (RT_BOOL(aNeedDhcpServer) == m->s.fNeedDhcpServer)
562 return S_OK;
563
564 m->s.fNeedDhcpServer = RT_BOOL(aNeedDhcpServer);
565
566 i_recalculateIpv4AddressAssignments();
567
568 }
569
570 AutoWriteLock vboxLock(m->pVirtualBox COMMA_LOCKVAL_SRC_POS);
571 HRESULT rc = m->pVirtualBox->i_saveSettings();
572 ComAssertComRCRetRC(rc);
573
574 return S_OK;
575}
576
577HRESULT NATNetwork::getLocalMappings(std::vector<com::Utf8Str> &aLocalMappings)
578{
579 AutoReadLock alock(this COMMA_LOCKVAL_SRC_POS);
580
581 aLocalMappings.resize(m->s.llHostLoopbackOffsetList.size());
582 size_t i = 0;
583 for (settings::NATLoopbackOffsetList::const_iterator it = m->s.llHostLoopbackOffsetList.begin();
584 it != m->s.llHostLoopbackOffsetList.end(); ++it, ++i)
585 {
586 aLocalMappings[i] = Utf8StrFmt("%s=%d",
587 (*it).strLoopbackHostAddress.c_str(),
588 (*it).u32Offset);
589 }
590
591 return S_OK;
592}
593
594HRESULT NATNetwork::addLocalMapping(const com::Utf8Str &aHostId, LONG aOffset)
595{
596 RTNETADDRIPV4 addr, net, mask;
597
598 int rc = RTNetStrToIPv4Addr(Utf8Str(aHostId).c_str(), &addr);
599 if (RT_FAILURE(rc))
600 return E_INVALIDARG;
601
602 /* check against 127/8 */
603 if ((RT_N2H_U32(addr.u) >> IN_CLASSA_NSHIFT) != IN_LOOPBACKNET)
604 return E_INVALIDARG;
605
606 /* check against networkid vs network mask */
607 rc = RTCidrStrToIPv4(Utf8Str(m->s.strIPv4NetworkCidr).c_str(), &net, &mask);
608 if (RT_FAILURE(rc))
609 return E_INVALIDARG;
610
611 if (((net.u + (uint32_t)aOffset) & mask.u) != net.u)
612 return E_INVALIDARG;
613
614 settings::NATLoopbackOffsetList::iterator it;
615
616 it = std::find(m->s.llHostLoopbackOffsetList.begin(),
617 m->s.llHostLoopbackOffsetList.end(),
618 aHostId);
619 if (it != m->s.llHostLoopbackOffsetList.end())
620 {
621 if (aOffset == 0) /* erase */
622 m->s.llHostLoopbackOffsetList.erase(it, it);
623 else /* modify */
624 {
625 settings::NATLoopbackOffsetList::iterator it1;
626 it1 = std::find(m->s.llHostLoopbackOffsetList.begin(),
627 m->s.llHostLoopbackOffsetList.end(),
628 (uint32_t)aOffset);
629 if (it1 != m->s.llHostLoopbackOffsetList.end())
630 return E_INVALIDARG; /* this offset is already registered. */
631
632 (*it).u32Offset = (uint32_t)aOffset;
633 }
634
635 AutoWriteLock vboxLock(m->pVirtualBox COMMA_LOCKVAL_SRC_POS);
636 return m->pVirtualBox->i_saveSettings();
637 }
638
639 /* injection */
640 it = std::find(m->s.llHostLoopbackOffsetList.begin(),
641 m->s.llHostLoopbackOffsetList.end(),
642 (uint32_t)aOffset);
643
644 if (it != m->s.llHostLoopbackOffsetList.end())
645 return E_INVALIDARG; /* offset is already registered. */
646
647 settings::NATHostLoopbackOffset off;
648 off.strLoopbackHostAddress = aHostId;
649 off.u32Offset = (uint32_t)aOffset;
650 m->s.llHostLoopbackOffsetList.push_back(off);
651
652 AutoWriteLock vboxLock(m->pVirtualBox COMMA_LOCKVAL_SRC_POS);
653 return m->pVirtualBox->i_saveSettings();
654}
655
656
657HRESULT NATNetwork::getLoopbackIp6(LONG *aLoopbackIp6)
658{
659 AutoReadLock alock(this COMMA_LOCKVAL_SRC_POS);
660
661 *aLoopbackIp6 = (LONG)m->s.u32HostLoopback6Offset;
662 return S_OK;
663}
664
665
666HRESULT NATNetwork::setLoopbackIp6(LONG aLoopbackIp6)
667{
668 {
669 AutoReadLock alockNatNetList(m->pVirtualBox->i_getNatNetLock() COMMA_LOCKVAL_SRC_POS);
670 if (m->pVirtualBox->i_isNatNetStarted(m->s.strNetworkName))
671 return setErrorBusy();
672
673 AutoWriteLock alock(this COMMA_LOCKVAL_SRC_POS);
674
675 if (aLoopbackIp6 < 0)
676 return E_INVALIDARG;
677
678 if (static_cast<uint32_t>(aLoopbackIp6) == m->s.u32HostLoopback6Offset)
679 return S_OK;
680
681 m->s.u32HostLoopback6Offset = (uint32_t)aLoopbackIp6;
682 }
683
684 AutoWriteLock vboxLock(m->pVirtualBox COMMA_LOCKVAL_SRC_POS);
685 return m->pVirtualBox->i_saveSettings();
686}
687
688
689HRESULT NATNetwork::getPortForwardRules4(std::vector<com::Utf8Str> &aPortForwardRules4)
690{
691 AutoReadLock alock(this COMMA_LOCKVAL_SRC_POS);
692 i_getPortForwardRulesFromMap(aPortForwardRules4,
693 m->s.mapPortForwardRules4);
694 return S_OK;
695}
696
697HRESULT NATNetwork::getPortForwardRules6(std::vector<com::Utf8Str> &aPortForwardRules6)
698{
699 AutoReadLock alock(this COMMA_LOCKVAL_SRC_POS);
700 i_getPortForwardRulesFromMap(aPortForwardRules6,
701 m->s.mapPortForwardRules6);
702 return S_OK;
703}
704
705HRESULT NATNetwork::addPortForwardRule(BOOL aIsIpv6,
706 const com::Utf8Str &aPortForwardRuleName,
707 NATProtocol_T aProto,
708 const com::Utf8Str &aHostIp,
709 USHORT aHostPort,
710 const com::Utf8Str &aGuestIp,
711 USHORT aGuestPort)
712{
713 {
714 AutoWriteLock alock(this COMMA_LOCKVAL_SRC_POS);
715 Utf8Str name = aPortForwardRuleName;
716 Utf8Str proto;
717 settings::NATRule r;
718 settings::NATRulesMap &mapRules = aIsIpv6 ? m->s.mapPortForwardRules6 : m->s.mapPortForwardRules4;
719 switch (aProto)
720 {
721 case NATProtocol_TCP:
722 proto = "tcp";
723 break;
724 case NATProtocol_UDP:
725 proto = "udp";
726 break;
727 default:
728 return E_INVALIDARG;
729 }
730 if (name.isEmpty())
731 name = Utf8StrFmt("%s_[%s]%%%d_[%s]%%%d", proto.c_str(),
732 aHostIp.c_str(), aHostPort,
733 aGuestIp.c_str(), aGuestPort);
734
735 for (settings::NATRulesMap::iterator it = mapRules.begin(); it != mapRules.end(); ++it)
736 {
737 r = it->second;
738 if (it->first == name)
739 return setError(E_INVALIDARG,
740 tr("A NAT rule of this name already exists"));
741 if ( r.strHostIP == aHostIp
742 && r.u16HostPort == aHostPort
743 && r.proto == aProto)
744 return setError(E_INVALIDARG,
745 tr("A NAT rule for this host port and this host IP already exists"));
746 }
747
748 r.strName = name.c_str();
749 r.proto = aProto;
750 r.strHostIP = aHostIp;
751 r.u16HostPort = aHostPort;
752 r.strGuestIP = aGuestIp;
753 r.u16GuestPort = aGuestPort;
754 mapRules.insert(std::make_pair(name, r));
755 }
756 {
757 AutoWriteLock vboxLock(m->pVirtualBox COMMA_LOCKVAL_SRC_POS);
758 HRESULT rc = m->pVirtualBox->i_saveSettings();
759 ComAssertComRCRetRC(rc);
760 }
761
762 m->pVirtualBox->i_onNATNetworkPortForward(m->s.strNetworkName, TRUE, aIsIpv6,
763 aPortForwardRuleName, aProto,
764 aHostIp, aHostPort,
765 aGuestIp, aGuestPort);
766
767 /* Notify listeners listening on this network only */
768 ::FireNATNetworkPortForwardEvent(m->pEventSource, m->s.strNetworkName, TRUE,
769 aIsIpv6, aPortForwardRuleName, aProto,
770 aHostIp, aHostPort,
771 aGuestIp, aGuestPort);
772
773 return S_OK;
774}
775
776HRESULT NATNetwork::removePortForwardRule(BOOL aIsIpv6, const com::Utf8Str &aPortForwardRuleName)
777{
778 Utf8Str strHostIP;
779 Utf8Str strGuestIP;
780 uint16_t u16HostPort;
781 uint16_t u16GuestPort;
782 NATProtocol_T proto;
783
784 {
785 AutoWriteLock alock(this COMMA_LOCKVAL_SRC_POS);
786 settings::NATRulesMap &mapRules = aIsIpv6 ? m->s.mapPortForwardRules6 : m->s.mapPortForwardRules4;
787 settings::NATRulesMap::iterator it = mapRules.find(aPortForwardRuleName);
788
789 if (it == mapRules.end())
790 return E_INVALIDARG;
791
792 strHostIP = it->second.strHostIP;
793 strGuestIP = it->second.strGuestIP;
794 u16HostPort = it->second.u16HostPort;
795 u16GuestPort = it->second.u16GuestPort;
796 proto = it->second.proto;
797
798 mapRules.erase(it);
799 }
800
801 {
802 AutoWriteLock vboxLock(m->pVirtualBox COMMA_LOCKVAL_SRC_POS);
803 HRESULT rc = m->pVirtualBox->i_saveSettings();
804 ComAssertComRCRetRC(rc);
805 }
806
807 m->pVirtualBox->i_onNATNetworkPortForward(m->s.strNetworkName, FALSE, aIsIpv6, aPortForwardRuleName, proto,
808 strHostIP, u16HostPort, strGuestIP, u16GuestPort);
809
810 /* Notify listeners listening on this network only */
811 ::FireNATNetworkPortForwardEvent(m->pEventSource, m->s.strNetworkName, FALSE, aIsIpv6, aPortForwardRuleName, proto,
812 strHostIP, u16HostPort, strGuestIP, u16GuestPort);
813 return S_OK;
814}
815
816
817void NATNetwork::i_updateDomainNameOption(ComPtr<IHost> &host)
818{
819 com::Bstr domain;
820 if (FAILED(host->COMGETTER(DomainName)(domain.asOutParam())))
821 LogRel(("NATNetwork: Failed to get host's domain name\n"));
822 ComPtr<IDHCPGlobalConfig> pDHCPConfig;
823 HRESULT hrc = m->dhcpServer->COMGETTER(GlobalConfig)(pDHCPConfig.asOutParam());
824 if (FAILED(hrc))
825 {
826 LogRel(("NATNetwork: Failed to get global DHCP config when updating domain name option with %Rhrc\n", hrc));
827 return;
828 }
829 if (domain.isNotEmpty())
830 {
831 hrc = pDHCPConfig->SetOption(DHCPOption_DomainName, DHCPOptionEncoding_Normal, domain.raw());
832 if (FAILED(hrc))
833 LogRel(("NATNetwork: Failed to add domain name option with %Rhrc\n", hrc));
834 }
835 else
836 pDHCPConfig->RemoveOption(DHCPOption_DomainName);
837}
838
839void NATNetwork::i_updateDomainNameServerOption(ComPtr<IHost> &host)
840{
841 RTNETADDRIPV4 networkid, netmask;
842
843 int rc = RTCidrStrToIPv4(m->s.strIPv4NetworkCidr.c_str(), &networkid, &netmask);
844 if (RT_FAILURE(rc))
845 {
846 LogRel(("NATNetwork: Failed to parse cidr %s with %Rrc\n", m->s.strIPv4NetworkCidr.c_str(), rc));
847 return;
848 }
849
850 /* XXX: these are returned, surprisingly, in host order */
851 networkid.u = RT_H2N_U32(networkid.u);
852 netmask.u = RT_H2N_U32(netmask.u);
853
854 com::SafeArray<BSTR> nameServers;
855 HRESULT hrc = host->COMGETTER(NameServers)(ComSafeArrayAsOutParam(nameServers));
856 if (FAILED(hrc))
857 {
858 LogRel(("NATNetwork: Failed to get name servers from host with %Rhrc\n", hrc));
859 return;
860 }
861 ComPtr<IDHCPGlobalConfig> pDHCPConfig;
862 hrc = m->dhcpServer->COMGETTER(GlobalConfig)(pDHCPConfig.asOutParam());
863 if (FAILED(hrc))
864 {
865 LogRel(("NATNetwork: Failed to get global DHCP config when updating domain name server option with %Rhrc\n", hrc));
866 return;
867 }
868
869 size_t cAddresses = nameServers.size();
870 if (cAddresses)
871 {
872 RTCList<RTCString> lstServers;
873 /* The following code was copied (and adapted a bit) from VBoxNetDhcp::hostDnsServers */
874 /*
875 * Recent fashion is to run dnsmasq on 127.0.1.1 which we
876 * currently can't map. If that's the only nameserver we've got,
877 * we need to use DNS proxy for VMs to reach it.
878 */
879 bool fUnmappedLoopback = false;
880
881 for (size_t i = 0; i < cAddresses; ++i)
882 {
883 RTNETADDRIPV4 addr;
884
885 com::Utf8Str strNameServerAddress(nameServers[i]);
886 rc = RTNetStrToIPv4Addr(strNameServerAddress.c_str(), &addr);
887 if (RT_FAILURE(rc))
888 {
889 LogRel(("NATNetwork: Failed to parse IP address %s with %Rrc\n", strNameServerAddress.c_str(), rc));
890 continue;
891 }
892
893 if (addr.u == INADDR_ANY)
894 {
895 /*
896 * This doesn't seem to be very well documented except for
897 * RTFS of res_init.c, but INADDR_ANY is a valid value for
898 * for "nameserver".
899 */
900 addr.u = RT_H2N_U32_C(INADDR_LOOPBACK);
901 }
902
903 if (addr.au8[0] == 127)
904 {
905 settings::NATLoopbackOffsetList::const_iterator it;
906
907 it = std::find(m->s.llHostLoopbackOffsetList.begin(),
908 m->s.llHostLoopbackOffsetList.end(),
909 strNameServerAddress);
910 if (it == m->s.llHostLoopbackOffsetList.end())
911 {
912 fUnmappedLoopback = true;
913 continue;
914 }
915 addr.u = RT_H2N_U32(RT_N2H_U32(networkid.u) + it->u32Offset);
916 }
917 lstServers.append(RTCStringFmt("%RTnaipv4", addr));
918 }
919
920 if (lstServers.isEmpty() && fUnmappedLoopback)
921 lstServers.append(RTCStringFmt("%RTnaipv4", networkid.u | RT_H2N_U32_C(1U))); /* proxy */
922
923 hrc = pDHCPConfig->SetOption(DHCPOption_DomainNameServers, DHCPOptionEncoding_Normal, Bstr(RTCString::join(lstServers, " ")).raw());
924 if (FAILED(hrc))
925 LogRel(("NATNetwork: Failed to add domain name server option '%s' with %Rhrc\n", RTCString::join(lstServers, " ").c_str(), hrc));
926 }
927 else
928 pDHCPConfig->RemoveOption(DHCPOption_DomainNameServers);
929}
930
931void NATNetwork::i_updateDnsOptions()
932{
933 ComPtr<IHost> host;
934 if (SUCCEEDED(m->pVirtualBox->COMGETTER(Host)(host.asOutParam())))
935 {
936 i_updateDomainNameOption(host);
937 i_updateDomainNameServerOption(host);
938 }
939}
940
941
942HRESULT NATNetwork::start()
943{
944#ifdef VBOX_WITH_NAT_SERVICE
945 if (!m->s.fEnabled) return S_OK;
946 AssertReturn(!m->s.strNetworkName.isEmpty(), E_FAIL);
947
948 m->NATRunner.resetArguments();
949 m->NATRunner.addArgPair(NetworkServiceRunner::kpszKeyNetwork, Utf8Str(m->s.strNetworkName).c_str());
950
951 /* No portforwarding rules from command-line, all will be fetched via API */
952
953 if (m->s.fNeedDhcpServer)
954 {
955 /*
956 * Just to as idea... via API (on creation user pass the cidr of network and)
957 * and we calculate it's addreses (mutable?).
958 */
959
960 /*
961 * Configuration and running DHCP server:
962 * 1. find server first createDHCPServer
963 * 2. if return status is E_INVALARG => server already exists just find and start.
964 * 3. if return status neither E_INVALRG nor S_OK => return E_FAIL
965 * 4. if return status S_OK proceed to DHCP server configuration
966 * 5. call setConfiguration() and pass all required parameters
967 * 6. start dhcp server.
968 */
969 HRESULT hrc = m->pVirtualBox->FindDHCPServerByNetworkName(Bstr(m->s.strNetworkName).raw(),
970 m->dhcpServer.asOutParam());
971 switch (hrc)
972 {
973 case E_INVALIDARG:
974 /* server haven't beeen found let create it then */
975 hrc = m->pVirtualBox->CreateDHCPServer(Bstr(m->s.strNetworkName).raw(),
976 m->dhcpServer.asOutParam());
977 if (FAILED(hrc))
978 return E_FAIL;
979 /* breakthrough */
980
981 {
982 LogFunc(("gateway: %s, dhcpserver:%s, dhcplowerip:%s, dhcpupperip:%s\n",
983 m->IPv4Gateway.c_str(),
984 m->IPv4DhcpServer.c_str(),
985 m->IPv4DhcpServerLowerIp.c_str(),
986 m->IPv4DhcpServerUpperIp.c_str()));
987
988 hrc = m->dhcpServer->COMSETTER(Enabled)(true);
989
990 hrc = m->dhcpServer->SetConfiguration(Bstr(m->IPv4DhcpServer).raw(),
991 Bstr(m->IPv4NetworkMask).raw(),
992 Bstr(m->IPv4DhcpServerLowerIp).raw(),
993 Bstr(m->IPv4DhcpServerUpperIp).raw());
994 }
995 case S_OK:
996 break;
997
998 default:
999 return E_FAIL;
1000 }
1001
1002#ifdef VBOX_WITH_DHCPD
1003 i_updateDnsOptions();
1004#endif /* VBOX_WITH_DHCPD */
1005 /* XXX: AddGlobalOption(DhcpOpt_Router,) - enables attachement of DhcpServer to Main (no longer true with VBoxNetDhcpd). */
1006 ComPtr<IDHCPGlobalConfig> pDHCPConfig;
1007 hrc = m->dhcpServer->COMGETTER(GlobalConfig)(pDHCPConfig.asOutParam());
1008 if (FAILED(hrc))
1009 {
1010 LogRel(("NATNetwork: Failed to get global DHCP config when updating IPv4 gateway option with %Rhrc\n", hrc));
1011 m->dhcpServer.setNull();
1012 return E_FAIL;
1013 }
1014 pDHCPConfig->SetOption(DHCPOption_Routers, DHCPOptionEncoding_Normal, Bstr(m->IPv4Gateway).raw());
1015
1016 hrc = m->dhcpServer->Start(Bstr::Empty.raw(), Bstr(TRUNKTYPE_WHATEVER).raw());
1017 if (FAILED(hrc))
1018 {
1019 m->dhcpServer.setNull();
1020 return E_FAIL;
1021 }
1022 }
1023
1024 if (RT_SUCCESS(m->NATRunner.start(false /* KillProcOnStop */)))
1025 {
1026 m->pVirtualBox->i_onNATNetworkStartStop(m->s.strNetworkName, TRUE);
1027 return S_OK;
1028 }
1029 /** @todo missing setError()! */
1030 return E_FAIL;
1031#else
1032 ReturnComNotImplemented();
1033#endif
1034}
1035
1036HRESULT NATNetwork::stop()
1037{
1038#ifdef VBOX_WITH_NAT_SERVICE
1039 m->pVirtualBox->i_onNATNetworkStartStop(m->s.strNetworkName, FALSE);
1040
1041 if (!m->dhcpServer.isNull())
1042 m->dhcpServer->Stop();
1043
1044 if (RT_SUCCESS(m->NATRunner.stop()))
1045 return S_OK;
1046
1047 /** @todo missing setError()! */
1048 return E_FAIL;
1049#else
1050 ReturnComNotImplemented();
1051#endif
1052}
1053
1054
1055void NATNetwork::i_getPortForwardRulesFromMap(std::vector<com::Utf8Str> &aPortForwardRules, settings::NATRulesMap &aRules)
1056{
1057 aPortForwardRules.resize(aRules.size());
1058 size_t i = 0;
1059 for (settings::NATRulesMap::const_iterator it = aRules.begin();
1060 it != aRules.end(); ++it, ++i)
1061 {
1062 settings::NATRule r = it->second;
1063 aPortForwardRules[i] = Utf8StrFmt("%s:%s:[%s]:%d:[%s]:%d",
1064 r.strName.c_str(),
1065 (r.proto == NATProtocol_TCP ? "tcp" : "udp"),
1066 r.strHostIP.c_str(),
1067 r.u16HostPort,
1068 r.strGuestIP.c_str(),
1069 r.u16GuestPort);
1070 }
1071}
1072
1073
1074int NATNetwork::i_findFirstAvailableOffset(ADDRESSLOOKUPTYPE addrType, uint32_t *poff)
1075{
1076 RTNETADDRIPV4 network, netmask;
1077
1078 int rc = RTCidrStrToIPv4(m->s.strIPv4NetworkCidr.c_str(),
1079 &network,
1080 &netmask);
1081 AssertRCReturn(rc, rc);
1082
1083 uint32_t off;
1084 for (off = 1; off < ~netmask.u; ++off)
1085 {
1086 bool skip = false;
1087 for (settings::NATLoopbackOffsetList::iterator it = m->s.llHostLoopbackOffsetList.begin();
1088 it != m->s.llHostLoopbackOffsetList.end();
1089 ++it)
1090 {
1091 if ((*it).u32Offset == off)
1092 {
1093 skip = true;
1094 break;
1095 }
1096
1097 }
1098
1099 if (skip)
1100 continue;
1101
1102 if (off == m->offGateway)
1103 {
1104 if (addrType == ADDR_GATEWAY)
1105 break;
1106 else
1107 continue;
1108 }
1109
1110 if (off == m->offDhcp)
1111 {
1112 if (addrType == ADDR_DHCP)
1113 break;
1114 else
1115 continue;
1116 }
1117
1118 if (!skip)
1119 break;
1120 }
1121
1122 if (poff)
1123 *poff = off;
1124
1125 return VINF_SUCCESS;
1126}
1127
1128int NATNetwork::i_recalculateIpv4AddressAssignments()
1129{
1130 RTNETADDRIPV4 network, netmask;
1131 int rc = RTCidrStrToIPv4(m->s.strIPv4NetworkCidr.c_str(),
1132 &network,
1133 &netmask);
1134 AssertRCReturn(rc, rc);
1135
1136 i_findFirstAvailableOffset(ADDR_GATEWAY, &m->offGateway);
1137 if (m->s.fNeedDhcpServer)
1138 i_findFirstAvailableOffset(ADDR_DHCP, &m->offDhcp);
1139
1140 /* I don't remember the reason CIDR calculated on the host. */
1141 RTNETADDRIPV4 gateway = network;
1142 gateway.u += m->offGateway;
1143 gateway.u = RT_H2N_U32(gateway.u);
1144 char szTmpIp[16];
1145 RTStrPrintf(szTmpIp, sizeof(szTmpIp), "%RTnaipv4", gateway);
1146 m->IPv4Gateway = szTmpIp;
1147
1148 if (m->s.fNeedDhcpServer)
1149 {
1150 RTNETADDRIPV4 dhcpserver = network;
1151 dhcpserver.u += m->offDhcp;
1152
1153 /* XXX: adding more services should change the math here */
1154 RTNETADDRIPV4 dhcplowerip = network;
1155 uint32_t offDhcpLowerIp;
1156 i_findFirstAvailableOffset(ADDR_DHCPLOWERIP, &offDhcpLowerIp);
1157 dhcplowerip.u = RT_H2N_U32(dhcplowerip.u + offDhcpLowerIp);
1158
1159 RTNETADDRIPV4 dhcpupperip;
1160 dhcpupperip.u = RT_H2N_U32((network.u | ~netmask.u) - 1);
1161
1162 dhcpserver.u = RT_H2N_U32(dhcpserver.u);
1163 network.u = RT_H2N_U32(network.u);
1164
1165 RTStrPrintf(szTmpIp, sizeof(szTmpIp), "%RTnaipv4", dhcpserver);
1166 m->IPv4DhcpServer = szTmpIp;
1167 RTStrPrintf(szTmpIp, sizeof(szTmpIp), "%RTnaipv4", dhcplowerip);
1168 m->IPv4DhcpServerLowerIp = szTmpIp;
1169 RTStrPrintf(szTmpIp, sizeof(szTmpIp), "%RTnaipv4", dhcpupperip);
1170 m->IPv4DhcpServerUpperIp = szTmpIp;
1171
1172 LogFunc(("network:%RTnaipv4, dhcpserver:%RTnaipv4, dhcplowerip:%RTnaipv4, dhcpupperip:%RTnaipv4\n",
1173 network, dhcpserver, dhcplowerip, dhcpupperip));
1174 }
1175
1176 /* we need IPv4NetworkMask for NAT's gw service start */
1177 netmask.u = RT_H2N_U32(netmask.u);
1178 RTStrPrintf(szTmpIp, 16, "%RTnaipv4", netmask);
1179 m->IPv4NetworkMask = szTmpIp;
1180
1181 LogFlowFunc(("getaway:%RTnaipv4, netmask:%RTnaipv4\n", gateway, netmask));
1182 return VINF_SUCCESS;
1183}
1184
1185
1186int NATNetwork::i_recalculateIPv6Prefix()
1187{
1188 int rc;
1189
1190 RTNETADDRIPV4 net, mask;
1191 rc = RTCidrStrToIPv4(Utf8Str(m->s.strIPv4NetworkCidr).c_str(), &net, &mask);
1192 if (RT_FAILURE(rc))
1193 return rc;
1194
1195 net.u = RT_H2N_U32(net.u); /* XXX: fix RTCidrStrToIPv4! */
1196
1197 /*
1198 * [fd17:625c:f037:XXXX::/64] - RFC 4193 (ULA) Locally Assigned
1199 * Global ID where XXXX, 16 bit Subnet ID, are two bytes from the
1200 * middle of the IPv4 address, e.g. :dead: for 10.222.173.1
1201 */
1202 RTNETADDRIPV6 prefix;
1203 RT_ZERO(prefix);
1204
1205 prefix.au8[0] = 0xFD;
1206 prefix.au8[1] = 0x17;
1207
1208 prefix.au8[2] = 0x62;
1209 prefix.au8[3] = 0x5C;
1210
1211 prefix.au8[4] = 0xF0;
1212 prefix.au8[5] = 0x37;
1213
1214 prefix.au8[6] = net.au8[1];
1215 prefix.au8[7] = net.au8[2];
1216
1217 char szBuf[32];
1218 RTStrPrintf(szBuf, sizeof(szBuf), "%RTnaipv6/64", &prefix);
1219
1220 m->s.strIPv6Prefix = szBuf;
1221 return VINF_SUCCESS;
1222}
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