VirtualBox

source: vbox/trunk/src/VBox/Frontends/VBoxManage/VBoxManageNATNetwork.cpp@ 89697

Last change on this file since 89697 was 88757, checked in by vboxsync, 4 years ago

VBoxManage/NATNetwork: Fix stray tab in previous. bugref:8124.

  • Property svn:eol-style set to native
  • Property svn:keywords set to Author Date Id Revision
File size: 19.4 KB
Line 
1/* $Id: VBoxManageNATNetwork.cpp 88757 2021-04-28 21:56:01Z vboxsync $ */
2/** @file
3 * VBoxManage - Implementation of NAT Network command command.
4 */
5
6/*
7 * Copyright (C) 2006-2020 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
19/*********************************************************************************************************************************
20* Header Files *
21*********************************************************************************************************************************/
22#ifndef VBOX_ONLY_DOCS
23
24#include <VBox/com/com.h>
25#include <VBox/com/array.h>
26#include <VBox/com/ErrorInfo.h>
27#include <VBox/com/errorprint.h>
28#include <VBox/com/VirtualBox.h>
29#endif /* !VBOX_ONLY_DOCS */
30
31#ifndef RT_OS_WINDOWS
32# include <netinet/in.h>
33#else
34/* from <ws2ipdef.h> */
35# define INET6_ADDRSTRLEN 65
36#endif
37
38#define IPv6
39
40#include <iprt/cdefs.h>
41#include <iprt/cidr.h>
42#include <iprt/param.h>
43#include <iprt/path.h>
44#include <iprt/stream.h>
45#include <iprt/string.h>
46#include <iprt/net.h>
47#include <iprt/getopt.h>
48#include <iprt/ctype.h>
49
50#include <VBox/log.h>
51
52#include <vector>
53#include <iprt/sanitized/string>
54
55#include "VBoxManage.h"
56#include "VBoxPortForwardString.h"
57
58#ifndef VBOX_ONLY_DOCS
59
60using namespace com;
61
62typedef enum
63{
64 OP_ADD = 1000,
65 OP_REMOVE,
66 OP_MODIFY,
67 OP_START,
68 OP_STOP
69} OPCODE;
70
71typedef struct PFNAME2DELETE
72{
73 char szName[PF_NAMELEN];
74 bool fIPv6;
75} PFNAME2DELETE, *PPFNAME2DELETE;
76
77typedef std::vector<PFNAME2DELETE> VPF2DELETE;
78typedef VPF2DELETE::const_iterator VPF2DELETEITERATOR;
79
80typedef std::vector<PORTFORWARDRULE> VPF2ADD;
81typedef VPF2ADD::const_iterator VPF2ADDITERATOR;
82
83typedef std::vector<std::string> LOOPBACK2DELETEADD;
84typedef LOOPBACK2DELETEADD::iterator LOOPBACK2DELETEADDITERATOR;
85
86static HRESULT printNATNetwork(const ComPtr<INATNetwork> &pNATNet)
87{
88 HRESULT rc;
89
90 do
91 {
92 Bstr strVal;
93 BOOL fVal;
94
95 CHECK_ERROR_BREAK(pNATNet, COMGETTER(NetworkName)(strVal.asOutParam()));
96 RTPrintf("Name: %ls\n", strVal.raw());
97
98 CHECK_ERROR_BREAK(pNATNet, COMGETTER(Network)(strVal.asOutParam()));
99 RTPrintf("Network: %ls\n", strVal.raw());
100
101 CHECK_ERROR_BREAK(pNATNet, COMGETTER(Gateway)(strVal.asOutParam()));
102 RTPrintf("Gateway: %ls\n", strVal.raw());
103
104 CHECK_ERROR_BREAK(pNATNet, COMGETTER(NeedDhcpServer)(&fVal));
105 RTPrintf("DHCP Sever: %s\n", fVal ? "Yes" : "No");
106
107 CHECK_ERROR_BREAK(pNATNet, COMGETTER(IPv6Enabled)(&fVal));
108 RTPrintf("IPv6: %s\n", fVal ? "Yes" : "No");
109
110 CHECK_ERROR_BREAK(pNATNet, COMGETTER(IPv6Prefix)(strVal.asOutParam()));
111 RTPrintf("IPv6 Prefix: %ls\n", strVal.raw());
112
113 CHECK_ERROR_BREAK(pNATNet, COMGETTER(AdvertiseDefaultIPv6RouteEnabled)(&fVal));
114 RTPrintf("IPv6 Default: %s\n", fVal ? "Yes" : "No");
115
116
117 CHECK_ERROR_BREAK(pNATNet, COMGETTER(Enabled)(&fVal));
118 RTPrintf("Enabled: %s\n", fVal ? "Yes" : "No");
119 /** @todo Add more information here. */
120 RTPrintf("\n");
121
122 } while (0);
123
124 return rc;
125}
126
127static RTEXITCODE handleNATList(HandlerArg *a)
128{
129 HRESULT rc;
130
131 RTPrintf("NAT Networks:\n\n");
132
133 const char *pszFilter = NULL;
134 if (a->argc > 1)
135 pszFilter = a->argv[1];
136
137 size_t cFound = 0;
138
139 com::SafeIfaceArray<INATNetwork> arrNetNets;
140 CHECK_ERROR(a->virtualBox, COMGETTER(NATNetworks)(ComSafeArrayAsOutParam(arrNetNets)));
141 for (size_t i = 0; i < arrNetNets.size(); ++i)
142 {
143 ComPtr<INATNetwork> pNATNet = arrNetNets[i];
144
145 if (pszFilter)
146 {
147 Bstr strVal;
148 CHECK_ERROR_BREAK(pNATNet, COMGETTER(NetworkName)(strVal.asOutParam()));
149
150 Utf8Str strValUTF8 = Utf8Str(strVal);
151 if (!RTStrSimplePatternMatch(pszFilter, strValUTF8.c_str()))
152 continue;
153 }
154
155 if (i > 0)
156 RTPrintf("\n");
157 rc = printNATNetwork(pNATNet);
158 if (FAILED(rc))
159 break;
160
161 cFound++;
162 }
163
164 if (SUCCEEDED(rc))
165 RTPrintf("%zu %s found\n", cFound, cFound == 1 ? "network" : "networks");
166
167 return SUCCEEDED(rc) ? RTEXITCODE_SUCCESS : RTEXITCODE_FAILURE;
168}
169
170static RTEXITCODE handleOp(HandlerArg *a, OPCODE enmCode)
171{
172 if (a->argc - 1 <= 1)
173 return errorSyntax(USAGE_NATNETWORK, "Not enough parameters");
174
175 const char *pNetName = NULL;
176 const char *pPrefixIPv4 = NULL;
177 const char *pPrefixIPv6 = NULL;
178 int enable = -1;
179 int dhcp = -1;
180 int ipv6 = -1;
181
182 VPF2DELETE vPfName2Delete;
183 VPF2ADD vPf2Add;
184
185 LOOPBACK2DELETEADD vLoopback2Delete;
186 LOOPBACK2DELETEADD vLoopback2Add;
187
188 LONG loopback6Offset = 0; /* ignore me */
189
190#define NATNET_CMD_OPT_IPV6_PREFIX (256 + '6')
191 static const RTGETOPTDEF g_aNATNetworkIPOptions[] =
192 {
193 { "--netname", 't', RTGETOPT_REQ_STRING },
194 { "--network", 'n', RTGETOPT_REQ_STRING }, /* old name */
195 { "--ipv4-prefix", 'n', RTGETOPT_REQ_STRING }, /* new name */
196 { "--dhcp", 'h', RTGETOPT_REQ_BOOL },
197 { "--ipv6", '6', RTGETOPT_REQ_BOOL }, /* old name */
198 { "--ipv6-enable", '6', RTGETOPT_REQ_BOOL }, /* new name */
199 { "--ipv6-prefix", NATNET_CMD_OPT_IPV6_PREFIX, RTGETOPT_REQ_STRING },
200 { "--enable", 'e', RTGETOPT_REQ_NOTHING },
201 { "--disable", 'd', RTGETOPT_REQ_NOTHING },
202 { "--port-forward-4", 'p', RTGETOPT_REQ_STRING },
203 { "--port-forward-6", 'P', RTGETOPT_REQ_STRING },
204 { "--loopback-4", 'l', RTGETOPT_REQ_STRING },
205 { "--loopback-6", 'L', RTGETOPT_REQ_STRING },
206 };
207
208 int c;
209 RTGETOPTUNION ValueUnion;
210 RTGETOPTSTATE GetState;
211 RTGetOptInit(&GetState, a->argc, a->argv, g_aNATNetworkIPOptions,
212 enmCode != OP_REMOVE ? RT_ELEMENTS(g_aNATNetworkIPOptions) : 4, /* we use only --netname and --ifname for remove*/
213 1, RTGETOPTINIT_FLAGS_NO_STD_OPTS);
214 while ((c = RTGetOpt(&GetState, &ValueUnion)) != 0)
215 {
216 switch (c)
217 {
218 case 't': // --netname
219 if (pNetName)
220 return errorSyntax(USAGE_NATNETWORK, "You can only specify --netname only once.");
221 pNetName = ValueUnion.psz;
222 break;
223
224 case 'n': // --network
225 if (pPrefixIPv4)
226 return errorSyntax(USAGE_NATNETWORK, "You can only specify --network only once.");
227 pPrefixIPv4 = ValueUnion.psz;
228 break;
229
230 case 'e': // --enable
231 if (enable >= 0)
232 return errorSyntax(USAGE_NATNETWORK, "You can specify either --enable or --disable once.");
233 enable = 1;
234 break;
235
236 case 'd': // --disable
237 if (enable >= 0)
238 return errorSyntax(USAGE_NATNETWORK, "You can specify either --enable or --disable once.");
239 enable = 0;
240 break;
241
242 case 'h':
243 if (dhcp != -1)
244 return errorSyntax(USAGE_NATNETWORK, "You can specify --dhcp only once.");
245 dhcp = ValueUnion.f;
246 break;
247
248 case '6':
249 if (ipv6 != -1)
250 return errorSyntax(USAGE_NATNETWORK, "You can specify --ipv6 only once.");
251 ipv6 = ValueUnion.f;
252 break;
253
254 case NATNET_CMD_OPT_IPV6_PREFIX:
255 if (pPrefixIPv6)
256 return errorSyntax(USAGE_NATNETWORK, "You can specify --ipv6-prefix only once.");
257 pPrefixIPv6 = ValueUnion.psz;
258 break;
259
260 case 'L': /* ipv6 loopback */
261 case 'l': /* ipv4 loopback */
262 if (RTStrCmp(ValueUnion.psz, "delete") == 0)
263 {
264 /* deletion */
265 if (enmCode != OP_MODIFY)
266 errorSyntax(USAGE_NATNETWORK,
267 "loopback couldn't be deleted on modified\n");
268 if (c == 'L')
269 loopback6Offset = -1;
270 else
271 {
272 int vrc;
273 RTGETOPTUNION Addr2Delete;
274 vrc = RTGetOptFetchValue(&GetState,
275 &Addr2Delete,
276 RTGETOPT_REQ_STRING);
277 if (RT_FAILURE(vrc))
278 return errorSyntax(USAGE_NATNETWORK,
279 "Not enough parmaters\n");
280
281 vLoopback2Delete.push_back(std::string(Addr2Delete.psz));
282 }
283 }
284 else
285 {
286 /* addition */
287 if (c == 'L')
288 loopback6Offset = ValueUnion.u32;
289 else
290 vLoopback2Add.push_back(std::string(ValueUnion.psz));
291 }
292 break;
293
294 case 'P': /* ipv6 portforwarding*/
295 case 'p': /* ipv4 portforwarding */
296 {
297 if (RTStrCmp(ValueUnion.psz, "delete") != 0)
298 {
299 /* addition */
300 /* netPfStrToPf will clean up the Pfr */
301 PORTFORWARDRULE Pfr;
302 int irc = netPfStrToPf(ValueUnion.psz, (c == 'P'), &Pfr);
303 if (RT_FAILURE(irc))
304 return errorSyntax(USAGE_NATNETWORK, "Invalid port-forward rule %s\n", ValueUnion.psz);
305
306 vPf2Add.push_back(Pfr);
307 }
308 else
309 {
310 /* deletion */
311 if (enmCode != OP_MODIFY)
312 return errorSyntax(USAGE_NATNETWORK,
313 "Port-forward could be deleted on modify \n");
314
315 RTGETOPTUNION NamePf2DeleteUnion;
316 int vrc = RTGetOptFetchValue(&GetState, &NamePf2DeleteUnion, RTGETOPT_REQ_STRING);
317 if (RT_FAILURE(vrc))
318 return errorSyntax(USAGE_NATNETWORK, "Not enough parmaters\n");
319
320 if (strlen(NamePf2DeleteUnion.psz) > PF_NAMELEN)
321 return errorSyntax(USAGE_NATNETWORK, "Port-forward rule name is too long\n");
322
323 PFNAME2DELETE Name2Delete;
324 RT_ZERO(Name2Delete);
325 RTStrCopy(Name2Delete.szName, PF_NAMELEN, NamePf2DeleteUnion.psz);
326 Name2Delete.fIPv6 = (c == 'P');
327 vPfName2Delete.push_back(Name2Delete);
328 }
329 break;
330 }
331
332 default:
333 return errorGetOpt(USAGE_NATNETWORK, c, &ValueUnion);
334 }
335 }
336
337 if (!pNetName)
338 return errorSyntax(USAGE_NATNETWORK, "You need to specify the --netname option");
339 /* verification */
340 switch (enmCode)
341 {
342 case OP_ADD:
343 if (!pPrefixIPv4)
344 return errorSyntax(USAGE_NATNETWORK, "You need to specify the --network option");
345 break;
346 case OP_MODIFY:
347 case OP_REMOVE:
348 case OP_START:
349 case OP_STOP:
350 break;
351 default:
352 AssertMsgFailedReturn(("Unknown operation (:%d)", enmCode), RTEXITCODE_FAILURE);
353 }
354
355 HRESULT rc;
356 Bstr NetName;
357 NetName = Bstr(pNetName);
358
359 ComPtr<INATNetwork> net;
360 rc = a->virtualBox->FindNATNetworkByName(NetName.mutableRaw(), net.asOutParam());
361 if (enmCode == OP_ADD)
362 {
363 if (SUCCEEDED(rc))
364 return errorArgument("NATNetwork server already exists");
365
366 CHECK_ERROR(a->virtualBox, CreateNATNetwork(NetName.raw(), net.asOutParam()));
367 if (FAILED(rc))
368 return errorArgument("Failed to create the NAT network service");
369 }
370 else if (FAILED(rc))
371 return errorArgument("NATNetwork server does not exist");
372
373 switch (enmCode)
374 {
375 case OP_ADD:
376 case OP_MODIFY:
377 {
378 if (pPrefixIPv4)
379 {
380 CHECK_ERROR(net, COMSETTER(Network)(Bstr(pPrefixIPv4).raw()));
381 if (FAILED(rc))
382 return errorArgument("Failed to set configuration");
383 }
384 if (dhcp >= 0)
385 {
386 CHECK_ERROR(net, COMSETTER(NeedDhcpServer) ((BOOL)dhcp));
387 if (FAILED(rc))
388 return errorArgument("Failed to set configuration");
389 }
390
391 /*
392 * If we are asked to disable IPv6, do it early so that
393 * the same command can also set IPv6 prefix to empty if
394 * it so wishes.
395 */
396 if (ipv6 == 0)
397 {
398 CHECK_ERROR(net, COMSETTER(IPv6Enabled)(FALSE));
399 if (FAILED(rc))
400 return errorArgument("Failed to set configuration");
401 }
402
403 if (pPrefixIPv6)
404 {
405 CHECK_ERROR(net, COMSETTER(IPv6Prefix)(Bstr(pPrefixIPv6).raw()));
406 if (FAILED(rc))
407 return errorArgument("Failed to set configuration");
408 }
409
410 /*
411 * If we are asked to enable IPv6, do it late, so that the
412 * same command can also set IPv6 prefix.
413 */
414 if (ipv6 > 0)
415 {
416 CHECK_ERROR(net, COMSETTER(IPv6Enabled)(TRUE));
417 if (FAILED(rc))
418 return errorArgument("Failed to set configuration");
419 }
420
421 if (!vPfName2Delete.empty())
422 {
423 VPF2DELETEITERATOR it;
424 for (it = vPfName2Delete.begin(); it != vPfName2Delete.end(); ++it)
425 {
426 CHECK_ERROR(net, RemovePortForwardRule((BOOL)(*it).fIPv6,
427 Bstr((*it).szName).raw()));
428 if (FAILED(rc))
429 return errorArgument("Failed to delete pf");
430 }
431 }
432
433 if (!vPf2Add.empty())
434 {
435 VPF2ADDITERATOR it;
436 for (it = vPf2Add.begin(); it != vPf2Add.end(); ++it)
437 {
438 NATProtocol_T proto = NATProtocol_TCP;
439 if ((*it).iPfrProto == IPPROTO_TCP)
440 proto = NATProtocol_TCP;
441 else if ((*it).iPfrProto == IPPROTO_UDP)
442 proto = NATProtocol_UDP;
443 else
444 continue; /* XXX: warning here. */
445
446 CHECK_ERROR(net, AddPortForwardRule((BOOL)(*it).fPfrIPv6,
447 Bstr((*it).szPfrName).raw(),
448 proto,
449 Bstr((*it).szPfrHostAddr).raw(),
450 (*it).u16PfrHostPort,
451 Bstr((*it).szPfrGuestAddr).raw(),
452 (*it).u16PfrGuestPort));
453 if (FAILED(rc))
454 return errorArgument("Failed to add pf");
455 }
456 }
457
458 if (loopback6Offset)
459 {
460 if (loopback6Offset == -1)
461 loopback6Offset = 0; /* deletion */
462
463 CHECK_ERROR_RET(net, COMSETTER(LoopbackIp6)(loopback6Offset), RTEXITCODE_FAILURE);
464 }
465
466 /* addLocalMapping (hostid, offset) */
467 if (!vLoopback2Add.empty())
468 {
469 /* we're expecting stings 127.0.0.1=5 */
470 LOOPBACK2DELETEADDITERATOR it;
471 for (it = vLoopback2Add.begin();
472 it != vLoopback2Add.end();
473 ++it)
474 {
475 std::string address, strOffset;
476 size_t pos = it->find('=');
477 LONG lOffset = 0;
478 Bstr bstrAddress;
479
480 AssertReturn(pos != std::string::npos, errorArgument("invalid loopback string"));
481
482 address = it->substr(0, pos);
483 strOffset = it->substr(pos + 1);
484
485 lOffset = RTStrToUInt32(strOffset.c_str());
486 AssertReturn(lOffset > 0, errorArgument("invalid loopback string"));
487
488 bstrAddress = Bstr(address.c_str());
489
490 CHECK_ERROR_RET(net, AddLocalMapping(bstrAddress.raw(), lOffset), RTEXITCODE_FAILURE);
491 }
492 }
493
494 if (!vLoopback2Delete.empty())
495 {
496 /* we're expecting stings 127.0.0.1 */
497 LOOPBACK2DELETEADDITERATOR it;
498 for (it = vLoopback2Add.begin();
499 it != vLoopback2Add.end();
500 ++it)
501 {
502 Bstr bstrAddress;
503 bstrAddress = Bstr(it->c_str());
504
505 CHECK_ERROR_RET(net, AddLocalMapping(bstrAddress.raw(), 0), RTEXITCODE_FAILURE);
506 }
507 }
508
509 if (enable >= 0)
510 {
511 CHECK_ERROR(net, COMSETTER(Enabled) ((BOOL)enable));
512 if (FAILED(rc))
513 return errorArgument("Failed to set configuration");
514 }
515 break;
516 }
517 case OP_REMOVE:
518 {
519 CHECK_ERROR(a->virtualBox, RemoveNATNetwork(net));
520 if (FAILED(rc))
521 return errorArgument("Failed to remove nat network");
522 break;
523 }
524 case OP_START:
525 {
526 CHECK_ERROR(net, Start());
527 if (FAILED(rc))
528 return errorArgument("Failed to start network");
529 break;
530 }
531 case OP_STOP:
532 {
533 CHECK_ERROR(net, Stop());
534 if (FAILED(rc))
535 return errorArgument("Failed to stop network");
536 break;
537 }
538 default:;
539 }
540 return RTEXITCODE_SUCCESS;
541}
542
543
544RTEXITCODE handleNATNetwork(HandlerArg *a)
545{
546 if (a->argc < 1)
547 return errorSyntax(USAGE_NATNETWORK, "Not enough parameters");
548
549 RTEXITCODE rcExit;
550 if (strcmp(a->argv[0], "modify") == 0)
551 rcExit = handleOp(a, OP_MODIFY);
552 else if (strcmp(a->argv[0], "add") == 0)
553 rcExit = handleOp(a, OP_ADD);
554 else if (strcmp(a->argv[0], "remove") == 0)
555 rcExit = handleOp(a, OP_REMOVE);
556 else if (strcmp(a->argv[0], "start") == 0)
557 rcExit = handleOp(a, OP_START);
558 else if (strcmp(a->argv[0], "stop") == 0)
559 rcExit = handleOp(a, OP_STOP);
560 else if (strcmp(a->argv[0], "list") == 0)
561 rcExit = handleNATList(a);
562 else
563 rcExit = errorSyntax(USAGE_NATNETWORK, "Invalid parameter '%s'", Utf8Str(a->argv[0]).c_str());
564 return rcExit;
565}
566
567#endif /* !VBOX_ONLY_DOCS */
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