VirtualBox

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

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

Main: bugref:1909: Added translation marks around messages of VBoxManage output

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