VirtualBox

source: vbox/trunk/src/VBox/NetworkServices/NAT/VBoxNetLwipNAT.cpp@ 86728

Last change on this file since 86728 was 85121, checked in by vboxsync, 4 years ago

iprt/cdefs.h: Refactored the typedef use of DECLCALLBACK as well as DECLCALLBACKMEMBER to wrap the whole expression, similar to the DECLR?CALLBACKMEMBER macros. This allows adding a throw() at the end when compiling with the VC++ compiler to indicate that the callbacks won't throw anything, so we can stop supressing the C5039 warning about passing functions that can potential throw C++ exceptions to extern C code that can't necessarily cope with such (unwind,++). Introduced a few _EX variations that allows specifying different/no calling convention too, as that's handy when dynamically resolving host APIs. Fixed numerous places missing DECLCALLBACK and such. Left two angry @todos regarding use of CreateThread. bugref:9794

  • Property svn:eol-style set to native
  • Property svn:keywords set to Author Date Id Revision
File size: 45.1 KB
Line 
1/* $Id: VBoxNetLwipNAT.cpp 85121 2020-07-08 19:33:26Z vboxsync $ */
2/** @file
3 * VBoxNetNAT - NAT Service for connecting to IntNet.
4 */
5
6/*
7 * Copyright (C) 2009-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/* Must be included before winutils.h (lwip/def.h), otherwise Windows build breaks. */
19#define LOG_GROUP LOG_GROUP_NAT_SERVICE
20
21#include "winutils.h"
22
23#include <VBox/com/assert.h>
24#include <VBox/com/com.h>
25#include <VBox/com/listeners.h>
26#include <VBox/com/string.h>
27#include <VBox/com/Guid.h>
28#include <VBox/com/array.h>
29#include <VBox/com/ErrorInfo.h>
30#include <VBox/com/errorprint.h>
31#include <VBox/com/VirtualBox.h>
32
33#include <iprt/net.h>
34#include <iprt/initterm.h>
35#include <iprt/alloca.h>
36#ifndef RT_OS_WINDOWS
37# include <arpa/inet.h>
38#endif
39#include <iprt/err.h>
40#include <iprt/time.h>
41#include <iprt/timer.h>
42#include <iprt/thread.h>
43#include <iprt/stream.h>
44#include <iprt/path.h>
45#include <iprt/param.h>
46#include <iprt/pipe.h>
47#include <iprt/getopt.h>
48#include <iprt/string.h>
49#include <iprt/mem.h>
50#include <iprt/message.h>
51#include <iprt/req.h>
52#include <iprt/file.h>
53#include <iprt/semaphore.h>
54#include <iprt/cpp/utils.h>
55#include <VBox/log.h>
56
57#include <VBox/sup.h>
58#include <VBox/intnet.h>
59#include <VBox/intnetinline.h>
60#include <VBox/vmm/pdmnetinline.h>
61#include <VBox/vmm/vmm.h>
62#include <VBox/version.h>
63
64#ifndef RT_OS_WINDOWS
65# include <sys/poll.h>
66# include <sys/socket.h>
67# include <netinet/in.h>
68# ifdef RT_OS_LINUX
69# include <linux/icmp.h> /* ICMP_FILTER */
70# endif
71# include <netinet/icmp6.h>
72#endif
73
74#include <map>
75#include <vector>
76#include <iprt/sanitized/string>
77
78#include <stdio.h>
79
80#include "../NetLib/VBoxNetLib.h"
81#include "../NetLib/VBoxNetBaseService.h"
82#include "../NetLib/utils.h"
83#include "VBoxLwipCore.h"
84
85extern "C"
86{
87/* bunch of LWIP headers */
88#include "lwip/sys.h"
89#include "lwip/pbuf.h"
90#include "lwip/netif.h"
91#include "lwip/ethip6.h"
92#include "lwip/nd6.h" // for proxy_na_hook
93#include "lwip/mld6.h"
94#include "lwip/tcpip.h"
95#include "netif/etharp.h"
96
97#include "proxy.h"
98#include "pxremap.h"
99#include "portfwd.h"
100}
101
102
103#if defined(VBOX_RAWSOCK_DEBUG_HELPER) \
104 && (defined(VBOX_WITH_HARDENING) \
105 || defined(RT_OS_WINDOWS) \
106 || defined(RT_OS_DARWIN))
107# error Have you forgotten to turn off VBOX_RAWSOCK_DEBUG_HELPER?
108#endif
109
110#ifdef VBOX_RAWSOCK_DEBUG_HELPER
111extern "C" int getrawsock(int type);
112#endif
113
114#include "../NetLib/VBoxPortForwardString.h"
115
116static RTGETOPTDEF g_aGetOptDef[] =
117{
118 { "--port-forward4", 'p', RTGETOPT_REQ_STRING },
119 { "--port-forward6", 'P', RTGETOPT_REQ_STRING }
120};
121
122typedef struct NATSEVICEPORTFORWARDRULE
123{
124 PORTFORWARDRULE Pfr;
125 fwspec FWSpec;
126} NATSEVICEPORTFORWARDRULE, *PNATSEVICEPORTFORWARDRULE;
127
128typedef std::vector<NATSEVICEPORTFORWARDRULE> VECNATSERVICEPF;
129typedef VECNATSERVICEPF::iterator ITERATORNATSERVICEPF;
130typedef VECNATSERVICEPF::const_iterator CITERATORNATSERVICEPF;
131
132static int fetchNatPortForwardRules(const ComNatPtr&, bool, VECNATSERVICEPF&);
133
134static int vboxNetNATLogInit(int argc, char **argv);
135
136
137class VBoxNetLwipNAT: public VBoxNetBaseService, public NATNetworkEventAdapter
138{
139 friend class NATNetworkListener;
140 public:
141 VBoxNetLwipNAT(SOCKET icmpsock4, SOCKET icmpsock6);
142 virtual ~VBoxNetLwipNAT();
143 void usage(){ /** @todo should be implemented */ };
144 int run();
145 virtual int init(void);
146 virtual int parseOpt(int rc, const RTGETOPTUNION& getOptVal);
147 /* VBoxNetNAT always needs Main */
148 virtual bool isMainNeeded() const { return true; }
149 virtual int processFrame(void *, size_t);
150 virtual int processGSO(PCPDMNETWORKGSO, size_t);
151 virtual int processUDP(void *, size_t) { return VERR_IGNORED; }
152
153 private:
154 struct proxy_options m_ProxyOptions;
155 struct sockaddr_in m_src4;
156 struct sockaddr_in6 m_src6;
157 /**
158 * place for registered local interfaces.
159 */
160 ip4_lomap m_lo2off[10];
161 ip4_lomap_desc m_loOptDescriptor;
162
163 uint16_t m_u16Mtu;
164 netif m_LwipNetIf;
165
166 /* Our NAT network descriptor in Main */
167 ComPtr<INATNetwork> m_net;
168 ComPtr<IHost> m_host;
169
170 ComNatListenerPtr m_NatListener;
171 ComNatListenerPtr m_VBoxListener;
172 ComNatListenerPtr m_VBoxClientListener;
173 static INTNETSEG aXmitSeg[64];
174
175 HRESULT HandleEvent(VBoxEventType_T aEventType, IEvent *pEvent);
176
177 const char **getHostNameservers();
178
179 /* Only for debug needs, by default NAT service should load rules from SVC
180 * on startup, and then on sync them on events.
181 */
182 bool fDontLoadRulesOnStartup;
183 static DECLCALLBACK(void) onLwipTcpIpInit(void *arg);
184 static DECLCALLBACK(void) onLwipTcpIpFini(void *arg);
185 static err_t netifInit(netif *pNetif) RT_NOTHROW_PROTO;
186 static err_t netifLinkoutput(netif *pNetif, pbuf *pBuf) RT_NOTHROW_PROTO;
187 /* static int intNetThreadRecv(RTTHREAD, void *); - unused */
188
189 VECNATSERVICEPF m_vecPortForwardRule4;
190 VECNATSERVICEPF m_vecPortForwardRule6;
191
192 static int natServicePfRegister(NATSEVICEPORTFORWARDRULE& natServicePf);
193 static int natServiceProcessRegisteredPf(VECNATSERVICEPF& vecPf);
194};
195
196
197static VBoxNetLwipNAT *g_pLwipNat;
198INTNETSEG VBoxNetLwipNAT::aXmitSeg[64];
199
200/**
201 * @note: this work on Event thread.
202 */
203HRESULT VBoxNetLwipNAT::HandleEvent(VBoxEventType_T aEventType, IEvent *pEvent)
204{
205 HRESULT hrc = S_OK;
206 switch (aEventType)
207 {
208 case VBoxEventType_OnNATNetworkSetting:
209 {
210 ComPtr<INATNetworkSettingEvent> pSettingsEvent(pEvent);
211
212 com::Bstr networkName;
213 hrc = pSettingsEvent->COMGETTER(NetworkName)(networkName.asOutParam());
214 AssertComRCReturn(hrc, hrc);
215 if (networkName.compare(getNetworkName().c_str()))
216 break; /* change not for our network */
217
218 // XXX: only handle IPv6 default route for now
219 if (!m_ProxyOptions.ipv6_enabled)
220 break;
221
222 BOOL fIPv6DefaultRoute = FALSE;
223 hrc = pSettingsEvent->COMGETTER(AdvertiseDefaultIPv6RouteEnabled)(&fIPv6DefaultRoute);
224 AssertComRCReturn(hrc, hrc);
225
226 if (m_ProxyOptions.ipv6_defroute == fIPv6DefaultRoute)
227 break;
228
229 m_ProxyOptions.ipv6_defroute = fIPv6DefaultRoute;
230 tcpip_callback_with_block(proxy_rtadvd_do_quick, &m_LwipNetIf, 0);
231 break;
232 }
233
234 case VBoxEventType_OnNATNetworkPortForward:
235 {
236 ComPtr<INATNetworkPortForwardEvent> pForwardEvent = pEvent;
237
238 com::Bstr networkName;
239 hrc = pForwardEvent->COMGETTER(NetworkName)(networkName.asOutParam());
240 AssertComRCReturn(hrc, hrc);
241 if (networkName.compare(getNetworkName().c_str()))
242 break; /* change not for our network */
243
244 BOOL fCreateFW;
245 hrc = pForwardEvent->COMGETTER(Create)(&fCreateFW);
246 AssertComRCReturn(hrc, hrc);
247
248 BOOL fIPv6FW;
249 hrc = pForwardEvent->COMGETTER(Ipv6)(&fIPv6FW);
250 AssertComRCReturn(hrc, hrc);
251
252 com::Bstr name;
253 hrc = pForwardEvent->COMGETTER(Name)(name.asOutParam());
254 AssertComRCReturn(hrc, hrc);
255
256 NATProtocol_T proto = NATProtocol_TCP;
257 hrc = pForwardEvent->COMGETTER(Proto)(&proto);
258 AssertComRCReturn(hrc, hrc);
259
260 com::Bstr strHostAddr;
261 hrc = pForwardEvent->COMGETTER(HostIp)(strHostAddr.asOutParam());
262 AssertComRCReturn(hrc, hrc);
263
264 LONG lHostPort;
265 hrc = pForwardEvent->COMGETTER(HostPort)(&lHostPort);
266 AssertComRCReturn(hrc, hrc);
267
268 com::Bstr strGuestAddr;
269 hrc = pForwardEvent->COMGETTER(GuestIp)(strGuestAddr.asOutParam());
270 AssertComRCReturn(hrc, hrc);
271
272 LONG lGuestPort;
273 hrc = pForwardEvent->COMGETTER(GuestPort)(&lGuestPort);
274 AssertComRCReturn(hrc, hrc);
275
276 VECNATSERVICEPF& rules = fIPv6FW ? m_vecPortForwardRule6
277 : m_vecPortForwardRule4;
278
279 NATSEVICEPORTFORWARDRULE r;
280 RT_ZERO(r);
281
282 r.Pfr.fPfrIPv6 = fIPv6FW;
283
284 switch (proto)
285 {
286 case NATProtocol_TCP:
287 r.Pfr.iPfrProto = IPPROTO_TCP;
288 break;
289 case NATProtocol_UDP:
290 r.Pfr.iPfrProto = IPPROTO_UDP;
291 break;
292
293 default:
294 LogRel(("Event: %s %s port-forwarding rule \"%s\": invalid protocol %d\n",
295 fCreateFW ? "Add" : "Remove",
296 fIPv6FW ? "IPv6" : "IPv4",
297 com::Utf8Str(name).c_str(),
298 (int)proto));
299 goto port_forward_done;
300 }
301
302 LogRel(("Event: %s %s port-forwarding rule \"%s\": %s %s%s%s:%d -> %s%s%s:%d\n",
303 fCreateFW ? "Add" : "Remove",
304 fIPv6FW ? "IPv6" : "IPv4",
305 com::Utf8Str(name).c_str(),
306 proto == NATProtocol_TCP ? "TCP" : "UDP",
307 /* from */
308 fIPv6FW ? "[" : "",
309 com::Utf8Str(strHostAddr).c_str(),
310 fIPv6FW ? "]" : "",
311 lHostPort,
312 /* to */
313 fIPv6FW ? "[" : "",
314 com::Utf8Str(strGuestAddr).c_str(),
315 fIPv6FW ? "]" : "",
316 lGuestPort));
317
318 if (name.length() > sizeof(r.Pfr.szPfrName))
319 {
320 hrc = E_INVALIDARG;
321 goto port_forward_done;
322 }
323
324 RTStrPrintf(r.Pfr.szPfrName, sizeof(r.Pfr.szPfrName),
325 "%s", com::Utf8Str(name).c_str());
326
327 RTStrPrintf(r.Pfr.szPfrHostAddr, sizeof(r.Pfr.szPfrHostAddr),
328 "%s", com::Utf8Str(strHostAddr).c_str());
329
330 /* XXX: limits should be checked */
331 r.Pfr.u16PfrHostPort = (uint16_t)lHostPort;
332
333 RTStrPrintf(r.Pfr.szPfrGuestAddr, sizeof(r.Pfr.szPfrGuestAddr),
334 "%s", com::Utf8Str(strGuestAddr).c_str());
335
336 /* XXX: limits should be checked */
337 r.Pfr.u16PfrGuestPort = (uint16_t)lGuestPort;
338
339 if (fCreateFW) /* Addition */
340 {
341 int rc = natServicePfRegister(r);
342 if (RT_SUCCESS(rc))
343 rules.push_back(r);
344 }
345 else /* Deletion */
346 {
347 ITERATORNATSERVICEPF it;
348 for (it = rules.begin(); it != rules.end(); ++it)
349 {
350 /* compare */
351 NATSEVICEPORTFORWARDRULE &natFw = *it;
352 if ( natFw.Pfr.iPfrProto == r.Pfr.iPfrProto
353 && natFw.Pfr.u16PfrHostPort == r.Pfr.u16PfrHostPort
354 && strncmp(natFw.Pfr.szPfrHostAddr, r.Pfr.szPfrHostAddr, INET6_ADDRSTRLEN) == 0
355 && natFw.Pfr.u16PfrGuestPort == r.Pfr.u16PfrGuestPort
356 && strncmp(natFw.Pfr.szPfrGuestAddr, r.Pfr.szPfrGuestAddr, INET6_ADDRSTRLEN) == 0)
357 {
358 fwspec *pFwCopy = (fwspec *)RTMemDup(&natFw.FWSpec, sizeof(natFw.FWSpec));
359 if (pFwCopy)
360 {
361 int status = portfwd_rule_del(pFwCopy);
362 if (status == 0)
363 rules.erase(it); /* (pFwCopy is owned by lwip thread now.) */
364 else
365 RTMemFree(pFwCopy);
366 }
367 break;
368 }
369 } /* loop over vector elements */
370 } /* condition add or delete */
371 port_forward_done:
372 /* clean up strings */
373 name.setNull();
374 strHostAddr.setNull();
375 strGuestAddr.setNull();
376 break;
377 }
378
379 case VBoxEventType_OnHostNameResolutionConfigurationChange:
380 {
381 const char **ppcszNameServers = getHostNameservers();
382 err_t error;
383
384 error = tcpip_callback_with_block(pxdns_set_nameservers,
385 ppcszNameServers,
386 /* :block */ 0);
387 if (error != ERR_OK && ppcszNameServers != NULL)
388 RTMemFree(ppcszNameServers);
389 break;
390 }
391
392 case VBoxEventType_OnNATNetworkStartStop:
393 {
394 ComPtr <INATNetworkStartStopEvent> pStartStopEvent = pEvent;
395
396 com::Bstr networkName;
397 hrc = pStartStopEvent->COMGETTER(NetworkName)(networkName.asOutParam());
398 AssertComRCReturn(hrc, hrc);
399 if (networkName.compare(getNetworkName().c_str()))
400 break; /* change not for our network */
401
402 BOOL fStart = TRUE;
403 hrc = pStartStopEvent->COMGETTER(StartEvent)(&fStart);
404 AssertComRCReturn(hrc, hrc);
405
406 if (!fStart)
407 shutdown();
408 break;
409 }
410
411 case VBoxEventType_OnVBoxSVCAvailabilityChanged:
412 {
413 LogRel(("VBoxSVC became unavailable, exiting.\n"));
414 shutdown();
415 break;
416 }
417
418 default: break; /* Shut up MSC. */
419 }
420 return hrc;
421}
422
423
424/*static*/ DECLCALLBACK(void) VBoxNetLwipNAT::onLwipTcpIpInit(void *arg)
425{
426 AssertPtrReturnVoid(arg);
427 VBoxNetLwipNAT *pNat = static_cast<VBoxNetLwipNAT *>(arg);
428
429 HRESULT hrc = com::Initialize();
430 Assert(!FAILED(hrc)); NOREF(hrc);
431
432 proxy_arp_hook = pxremap_proxy_arp;
433 proxy_ip4_divert_hook = pxremap_ip4_divert;
434
435 proxy_na_hook = pxremap_proxy_na;
436 proxy_ip6_divert_hook = pxremap_ip6_divert;
437
438 /* lwip thread */
439 RTNETADDRIPV4 network;
440 RTNETADDRIPV4 address = g_pLwipNat->getIpv4Address();
441 RTNETADDRIPV4 netmask = g_pLwipNat->getIpv4Netmask();
442 network.u = address.u & netmask.u;
443
444 ip_addr LwipIpAddr, LwipIpNetMask, LwipIpNetwork;
445
446 memcpy(&LwipIpAddr, &address, sizeof(ip_addr));
447 memcpy(&LwipIpNetMask, &netmask, sizeof(ip_addr));
448 memcpy(&LwipIpNetwork, &network, sizeof(ip_addr));
449
450 netif *pNetif = netif_add(&g_pLwipNat->m_LwipNetIf /* Lwip Interface */,
451 &LwipIpAddr /* IP address*/,
452 &LwipIpNetMask /* Network mask */,
453 &LwipIpAddr /* gateway address, @todo: is self IP acceptable? */,
454 g_pLwipNat /* state */,
455 VBoxNetLwipNAT::netifInit /* netif_init_fn */,
456 tcpip_input /* netif_input_fn */);
457
458 AssertPtrReturnVoid(pNetif);
459
460 LogRel(("netif %c%c%d: mac %RTmac\n",
461 pNetif->name[0], pNetif->name[1], pNetif->num,
462 pNetif->hwaddr));
463 LogRel(("netif %c%c%d: inet %RTnaipv4 netmask %RTnaipv4\n",
464 pNetif->name[0], pNetif->name[1], pNetif->num,
465 pNetif->ip_addr, pNetif->netmask));
466 for (int i = 0; i < LWIP_IPV6_NUM_ADDRESSES; ++i) {
467 if (!ip6_addr_isinvalid(netif_ip6_addr_state(pNetif, i))) {
468 LogRel(("netif %c%c%d: inet6 %RTnaipv6\n",
469 pNetif->name[0], pNetif->name[1], pNetif->num,
470 netif_ip6_addr(pNetif, i)));
471 }
472 }
473
474 netif_set_up(pNetif);
475 netif_set_link_up(pNetif);
476
477 if (pNat->m_ProxyOptions.ipv6_enabled) {
478 /*
479 * XXX: lwIP currently only ever calls mld6_joingroup() in
480 * nd6_tmr() for fresh tentative addresses, which is a wrong place
481 * to do it - but I'm not keen on fixing this properly for now
482 * (with correct handling of interface up and down transitions,
483 * etc). So stick it here as a kludge.
484 */
485 for (int i = 0; i <= 1; ++i) {
486 ip6_addr_t *paddr = netif_ip6_addr(pNetif, i);
487
488 ip6_addr_t solicited_node_multicast_address;
489 ip6_addr_set_solicitednode(&solicited_node_multicast_address,
490 paddr->addr[3]);
491 mld6_joingroup(paddr, &solicited_node_multicast_address);
492 }
493
494 /*
495 * XXX: We must join the solicited-node multicast for the
496 * addresses we do IPv6 NA-proxy for. We map IPv6 loopback to
497 * proxy address + 1. We only need the low 24 bits, and those are
498 * fixed.
499 */
500 {
501 ip6_addr_t solicited_node_multicast_address;
502
503 ip6_addr_set_solicitednode(&solicited_node_multicast_address,
504 /* last 24 bits of the address */
505 PP_HTONL(0x00000002));
506 mld6_netif_joingroup(pNetif, &solicited_node_multicast_address);
507 }
508 }
509
510 proxy_init(&g_pLwipNat->m_LwipNetIf, &g_pLwipNat->m_ProxyOptions);
511
512 natServiceProcessRegisteredPf(g_pLwipNat->m_vecPortForwardRule4);
513 natServiceProcessRegisteredPf(g_pLwipNat->m_vecPortForwardRule6);
514}
515
516
517/*static*/ DECLCALLBACK(void) VBoxNetLwipNAT::onLwipTcpIpFini(void* arg)
518{
519 AssertPtrReturnVoid(arg);
520
521 /* XXX: proxy finalization */
522 netif_set_link_down(&g_pLwipNat->m_LwipNetIf);
523 netif_set_down(&g_pLwipNat->m_LwipNetIf);
524 netif_remove(&g_pLwipNat->m_LwipNetIf);
525
526}
527
528/*
529 * Callback for netif_add() to initialize the interface.
530 */
531/*static*/ err_t VBoxNetLwipNAT::netifInit(netif *pNetif) RT_NOTHROW_DEF
532{
533 err_t rcLwip = ERR_OK;
534
535 AssertPtrReturn(pNetif, ERR_ARG);
536
537 VBoxNetLwipNAT *pNat = static_cast<VBoxNetLwipNAT *>(pNetif->state);
538 AssertPtrReturn(pNat, ERR_ARG);
539
540 LogFlowFunc(("ENTER: pNetif[%c%c%d]\n", pNetif->name[0], pNetif->name[1], pNetif->num));
541 /* validity */
542 AssertReturn( pNetif->name[0] == 'N'
543 && pNetif->name[1] == 'T', ERR_ARG);
544
545
546 pNetif->hwaddr_len = sizeof(RTMAC);
547 RTMAC mac = g_pLwipNat->getMacAddress();
548 memcpy(pNetif->hwaddr, &mac, sizeof(RTMAC));
549
550 pNat->m_u16Mtu = 1500; // XXX: FIXME
551 pNetif->mtu = pNat->m_u16Mtu;
552
553 pNetif->flags = NETIF_FLAG_BROADCAST
554 | NETIF_FLAG_ETHARP /* Don't bother driver with ARP and let Lwip resolve ARP handling */
555 | NETIF_FLAG_ETHERNET; /* Lwip works with ethernet too */
556
557 pNetif->linkoutput = netifLinkoutput; /* ether-level-pipe */
558 pNetif->output = etharp_output; /* ip-pipe */
559
560 if (pNat->m_ProxyOptions.ipv6_enabled) {
561 pNetif->output_ip6 = ethip6_output;
562
563 /* IPv6 link-local address in slot 0 */
564 netif_create_ip6_linklocal_address(pNetif, /* :from_mac_48bit */ 1);
565 netif_ip6_addr_set_state(pNetif, 0, IP6_ADDR_PREFERRED); // skip DAD
566
567 /*
568 * RFC 4193 Locally Assigned Global ID (ULA) in slot 1
569 * [fd17:625c:f037:XXXX::1] where XXXX, 16 bit Subnet ID, are two
570 * bytes from the middle of the IPv4 address, e.g. :dead: for
571 * 10.222.173.1
572 */
573 u8_t nethi = ip4_addr2(&pNetif->ip_addr);
574 u8_t netlo = ip4_addr3(&pNetif->ip_addr);
575
576 ip6_addr_t *paddr = netif_ip6_addr(pNetif, 1);
577 IP6_ADDR(paddr, 0, 0xFD, 0x17, 0x62, 0x5C);
578 IP6_ADDR(paddr, 1, 0xF0, 0x37, nethi, netlo);
579 IP6_ADDR(paddr, 2, 0x00, 0x00, 0x00, 0x00);
580 IP6_ADDR(paddr, 3, 0x00, 0x00, 0x00, 0x01);
581 netif_ip6_addr_set_state(pNetif, 1, IP6_ADDR_PREFERRED);
582
583#if LWIP_IPV6_SEND_ROUTER_SOLICIT
584 pNetif->rs_count = 0;
585#endif
586 }
587
588 LogFlowFunc(("LEAVE: %d\n", rcLwip));
589 return rcLwip;
590}
591
592
593/*static*/ err_t VBoxNetLwipNAT::netifLinkoutput(netif *pNetif, pbuf *pPBuf) RT_NOTHROW_DEF
594{
595 AssertPtrReturn(pNetif, ERR_ARG);
596 AssertPtrReturn(pPBuf, ERR_ARG);
597
598 VBoxNetLwipNAT *self = static_cast<VBoxNetLwipNAT *>(pNetif->state);
599 AssertPtrReturn(self, ERR_IF);
600 AssertReturn(self == g_pLwipNat, ERR_ARG);
601
602 LogFlowFunc(("ENTER: pNetif[%c%c%d], pPbuf:%p\n",
603 pNetif->name[0],
604 pNetif->name[1],
605 pNetif->num,
606 pPBuf));
607
608 RT_ZERO(VBoxNetLwipNAT::aXmitSeg);
609
610 size_t idx = 0;
611 for (struct pbuf *q = pPBuf; q != NULL; q = q->next, ++idx)
612 {
613 AssertReturn(idx < RT_ELEMENTS(VBoxNetLwipNAT::aXmitSeg), ERR_MEM);
614
615#if ETH_PAD_SIZE
616 if (q == pPBuf)
617 {
618 VBoxNetLwipNAT::aXmitSeg[idx].pv = (uint8_t *)q->payload + ETH_PAD_SIZE;
619 VBoxNetLwipNAT::aXmitSeg[idx].cb = q->len - ETH_PAD_SIZE;
620 }
621 else
622#endif
623 {
624 VBoxNetLwipNAT::aXmitSeg[idx].pv = q->payload;
625 VBoxNetLwipNAT::aXmitSeg[idx].cb = q->len;
626 }
627 }
628
629 int rc = self->sendBufferOnWire(VBoxNetLwipNAT::aXmitSeg, idx,
630 pPBuf->tot_len - ETH_PAD_SIZE);
631 AssertRCReturn(rc, ERR_IF);
632
633 self->flushWire();
634
635 LogFlowFunc(("LEAVE: %d\n", ERR_OK));
636 return ERR_OK;
637}
638
639
640VBoxNetLwipNAT::VBoxNetLwipNAT(SOCKET icmpsock4, SOCKET icmpsock6) : VBoxNetBaseService("VBoxNetNAT", "nat-network")
641{
642 LogFlowFuncEnter();
643
644 m_ProxyOptions.ipv6_enabled = 0;
645 m_ProxyOptions.ipv6_defroute = 0;
646 m_ProxyOptions.icmpsock4 = icmpsock4;
647 m_ProxyOptions.icmpsock6 = icmpsock6;
648 m_ProxyOptions.tftp_root = NULL;
649 m_ProxyOptions.src4 = NULL;
650 m_ProxyOptions.src6 = NULL;
651 RT_ZERO(m_src4);
652 RT_ZERO(m_src6);
653 m_src4.sin_family = AF_INET;
654 m_src6.sin6_family = AF_INET6;
655#if HAVE_SA_LEN
656 m_src4.sin_len = sizeof(m_src4);
657 m_src6.sin6_len = sizeof(m_src6);
658#endif
659 m_ProxyOptions.nameservers = NULL;
660
661 m_LwipNetIf.name[0] = 'N';
662 m_LwipNetIf.name[1] = 'T';
663
664 RTMAC mac;
665 mac.au8[0] = 0x52;
666 mac.au8[1] = 0x54;
667 mac.au8[2] = 0;
668 mac.au8[3] = 0x12;
669 mac.au8[4] = 0x35;
670 mac.au8[5] = 0;
671 setMacAddress(mac);
672
673 RTNETADDRIPV4 address;
674 address.u = RT_MAKE_U32_FROM_U8( 10, 0, 2, 2); // NB: big-endian
675 setIpv4Address(address);
676
677 address.u = RT_H2N_U32_C(0xffffff00);
678 setIpv4Netmask(address);
679
680 fDontLoadRulesOnStartup = false;
681
682 for(unsigned int i = 0; i < RT_ELEMENTS(g_aGetOptDef); ++i)
683 addCommandLineOption(&g_aGetOptDef[i]);
684
685 LogFlowFuncLeave();
686}
687
688
689VBoxNetLwipNAT::~VBoxNetLwipNAT()
690{
691 if (m_ProxyOptions.tftp_root)
692 {
693 RTStrFree((char *)m_ProxyOptions.tftp_root);
694 m_ProxyOptions.tftp_root = NULL;
695 }
696 if (m_ProxyOptions.nameservers)
697 {
698 const char **pv = m_ProxyOptions.nameservers;
699 while (*pv)
700 {
701 RTStrFree((char*)*pv);
702 pv++;
703 }
704 RTMemFree(m_ProxyOptions.nameservers);
705 m_ProxyOptions.nameservers = NULL;
706 }
707}
708
709
710/*static*/ int VBoxNetLwipNAT::natServicePfRegister(NATSEVICEPORTFORWARDRULE& natPf)
711{
712 int lrc;
713
714 int sockFamily = (natPf.Pfr.fPfrIPv6 ? PF_INET6 : PF_INET);
715 int socketSpec;
716 switch(natPf.Pfr.iPfrProto)
717 {
718 case IPPROTO_TCP:
719 socketSpec = SOCK_STREAM;
720 break;
721 case IPPROTO_UDP:
722 socketSpec = SOCK_DGRAM;
723 break;
724 default:
725 return VERR_IGNORED;
726 }
727
728 const char *pszHostAddr = natPf.Pfr.szPfrHostAddr;
729 if (pszHostAddr[0] == '\0')
730 {
731 if (sockFamily == PF_INET)
732 pszHostAddr = "0.0.0.0";
733 else
734 pszHostAddr = "::";
735 }
736
737 lrc = fwspec_set(&natPf.FWSpec,
738 sockFamily,
739 socketSpec,
740 pszHostAddr,
741 natPf.Pfr.u16PfrHostPort,
742 natPf.Pfr.szPfrGuestAddr,
743 natPf.Pfr.u16PfrGuestPort);
744 if (lrc != 0)
745 return VERR_IGNORED;
746
747 fwspec *pFwCopy = (fwspec *)RTMemDup(&natPf.FWSpec, sizeof(natPf.FWSpec));
748 if (pFwCopy)
749 {
750 lrc = portfwd_rule_add(pFwCopy);
751 if (lrc == 0)
752 return VINF_SUCCESS; /* (pFwCopy is owned by lwip thread now.) */
753 RTMemFree(pFwCopy);
754 }
755 else
756 LogRel(("Unable to allocate memory for %s rule \"%s\"\n",
757 natPf.Pfr.fPfrIPv6 ? "IPv6" : "IPv4",
758 natPf.Pfr.szPfrName));
759 return VERR_IGNORED;
760}
761
762
763/*static*/ int VBoxNetLwipNAT::natServiceProcessRegisteredPf(VECNATSERVICEPF& vecRules)
764{
765 ITERATORNATSERVICEPF it;
766 for (it = vecRules.begin(); it != vecRules.end(); ++it)
767 {
768 NATSEVICEPORTFORWARDRULE &natPf = *it;
769
770 LogRel(("Loading %s port-forwarding rule \"%s\": %s %s%s%s:%d -> %s%s%s:%d\n",
771 natPf.Pfr.fPfrIPv6 ? "IPv6" : "IPv4",
772 natPf.Pfr.szPfrName,
773 natPf.Pfr.iPfrProto == IPPROTO_TCP ? "TCP" : "UDP",
774 /* from */
775 natPf.Pfr.fPfrIPv6 ? "[" : "",
776 natPf.Pfr.szPfrHostAddr,
777 natPf.Pfr.fPfrIPv6 ? "]" : "",
778 natPf.Pfr.u16PfrHostPort,
779 /* to */
780 natPf.Pfr.fPfrIPv6 ? "[" : "",
781 natPf.Pfr.szPfrGuestAddr,
782 natPf.Pfr.fPfrIPv6 ? "]" : "",
783 natPf.Pfr.u16PfrGuestPort));
784
785 natServicePfRegister(natPf);
786 }
787
788 return VINF_SUCCESS;
789}
790
791
792/**
793 * Main thread. Starts also the LWIP thread.
794 */
795int VBoxNetLwipNAT::init()
796{
797 LogFlowFuncEnter();
798
799 /* virtualbox initialized in super class */
800 int rc = ::VBoxNetBaseService::init();
801 AssertRCReturn(rc, rc);
802
803 std::string networkName = getNetworkName();
804 rc = findNatNetwork(virtualbox, networkName, m_net);
805 AssertRCReturn(rc, rc);
806
807 {
808 ComEventTypeArray eventTypes;
809 eventTypes.push_back(VBoxEventType_OnNATNetworkPortForward);
810 eventTypes.push_back(VBoxEventType_OnNATNetworkSetting);
811 rc = createNatListener(m_NatListener, virtualbox, this, eventTypes);
812 AssertRCReturn(rc, rc);
813 }
814
815
816 // resolver changes are reported on vbox but are retrieved from
817 // host so stash a pointer for future lookups
818 HRESULT hrc = virtualbox->COMGETTER(Host)(m_host.asOutParam());
819 AssertComRCReturn(hrc, VERR_INTERNAL_ERROR);
820
821 {
822 ComEventTypeArray eventTypes;
823 eventTypes.push_back(VBoxEventType_OnHostNameResolutionConfigurationChange);
824 eventTypes.push_back(VBoxEventType_OnNATNetworkStartStop);
825 rc = createNatListener(m_VBoxListener, virtualbox, this, eventTypes);
826 AssertRCReturn(rc, rc);
827 }
828
829 {
830 ComEventTypeArray eventTypes;
831 eventTypes.push_back(VBoxEventType_OnVBoxSVCAvailabilityChanged);
832 rc = createClientListener(m_VBoxClientListener, virtualboxClient, this, eventTypes);
833 AssertRCReturn(rc, rc);
834 }
835
836 BOOL fIPv6Enabled = FALSE;
837 hrc = m_net->COMGETTER(IPv6Enabled)(&fIPv6Enabled);
838 AssertComRCReturn(hrc, VERR_NOT_FOUND);
839
840 BOOL fIPv6DefaultRoute = FALSE;
841 if (fIPv6Enabled)
842 {
843 hrc = m_net->COMGETTER(AdvertiseDefaultIPv6RouteEnabled)(&fIPv6DefaultRoute);
844 AssertComRCReturn(hrc, VERR_NOT_FOUND);
845 }
846
847 m_ProxyOptions.ipv6_enabled = fIPv6Enabled;
848 m_ProxyOptions.ipv6_defroute = fIPv6DefaultRoute;
849
850
851 /*
852 * Bind outgoing connections to the specified IP.
853 */
854 com::Bstr bstrSourceIpX;
855
856 /* IPv4 */
857 com::Bstr bstrSourceIp4Key = com::BstrFmt("NAT/%s/SourceIp4", networkName.c_str());
858 hrc = virtualbox->GetExtraData(bstrSourceIp4Key.raw(), bstrSourceIpX.asOutParam());
859 if (SUCCEEDED(hrc) && bstrSourceIpX.isNotEmpty())
860 {
861 RTNETADDRIPV4 addr;
862 rc = RTNetStrToIPv4Addr(com::Utf8Str(bstrSourceIpX).c_str(), &addr);
863 if (RT_SUCCESS(rc))
864 {
865 m_src4.sin_addr.s_addr = addr.u;
866 m_ProxyOptions.src4 = &m_src4;
867
868 LogRel(("Will use %RTnaipv4 as IPv4 source address\n",
869 m_src4.sin_addr.s_addr));
870 }
871 else
872 {
873 LogRel(("Failed to parse \"%s\" IPv4 source address specification\n",
874 com::Utf8Str(bstrSourceIpX).c_str()));
875 }
876
877 bstrSourceIpX.setNull();
878 }
879
880 /* IPv6 */
881 com::Bstr bstrSourceIp6Key = com::BstrFmt("NAT/%s/SourceIp6", networkName.c_str());
882 hrc = virtualbox->GetExtraData(bstrSourceIp6Key.raw(), bstrSourceIpX.asOutParam());
883 if (SUCCEEDED(hrc) && bstrSourceIpX.isNotEmpty())
884 {
885 RTNETADDRIPV6 addr;
886 char *pszZone = NULL;
887 rc = RTNetStrToIPv6Addr(com::Utf8Str(bstrSourceIpX).c_str(), &addr, &pszZone);
888 if (RT_SUCCESS(rc))
889 {
890 memcpy(&m_src6.sin6_addr, &addr, sizeof(addr));
891 m_ProxyOptions.src6 = &m_src6;
892
893 LogRel(("Will use %RTnaipv6 as IPv6 source address\n",
894 &m_src6.sin6_addr));
895 }
896 else
897 {
898 LogRel(("Failed to parse \"%s\" IPv6 source address specification\n",
899 com::Utf8Str(bstrSourceIpX).c_str()));
900 }
901
902 bstrSourceIpX.setNull();
903 }
904
905
906 if (!fDontLoadRulesOnStartup)
907 {
908 fetchNatPortForwardRules(m_net, false, m_vecPortForwardRule4);
909 fetchNatPortForwardRules(m_net, true, m_vecPortForwardRule6);
910 } /* if (!fDontLoadRulesOnStartup) */
911
912 AddressToOffsetMapping tmp;
913 rc = localMappings(m_net, tmp);
914 if (RT_SUCCESS(rc) && !tmp.empty())
915 {
916 unsigned long i = 0;
917 for (AddressToOffsetMapping::iterator it = tmp.begin();
918 it != tmp.end() && i < RT_ELEMENTS(m_lo2off);
919 ++it, ++i)
920 {
921 ip4_addr_set_u32(&m_lo2off[i].loaddr, it->first.u);
922 m_lo2off[i].off = it->second;
923 }
924
925 m_loOptDescriptor.lomap = m_lo2off;
926 m_loOptDescriptor.num_lomap = i;
927 m_ProxyOptions.lomap_desc = &m_loOptDescriptor;
928 }
929
930 com::Bstr bstr;
931 hrc = virtualbox->COMGETTER(HomeFolder)(bstr.asOutParam());
932 AssertComRCReturn(hrc, VERR_NOT_FOUND);
933 if (!bstr.isEmpty())
934 {
935 com::Utf8Str strTftpRoot(com::Utf8StrFmt("%ls%c%s",
936 bstr.raw(), RTPATH_DELIMITER, "TFTP"));
937 char *pszStrTemp; // avoid const char ** vs char **
938 rc = RTStrUtf8ToCurrentCP(&pszStrTemp, strTftpRoot.c_str());
939 AssertRC(rc);
940 m_ProxyOptions.tftp_root = pszStrTemp;
941 }
942
943 m_ProxyOptions.nameservers = getHostNameservers();
944
945 /* end of COM initialization */
946
947 rc = g_pLwipNat->tryGoOnline();
948 if (RT_FAILURE(rc))
949 return rc;
950
951 /* this starts LWIP thread */
952 vboxLwipCoreInitialize(VBoxNetLwipNAT::onLwipTcpIpInit, this);
953
954 LogFlowFuncLeaveRC(rc);
955 return rc;
956}
957
958
959const char **VBoxNetLwipNAT::getHostNameservers()
960{
961 if (m_host.isNull())
962 return NULL;
963
964 com::SafeArray<BSTR> aNameServers;
965 HRESULT hrc = m_host->COMGETTER(NameServers)(ComSafeArrayAsOutParam(aNameServers));
966 if (FAILED(hrc))
967 return NULL;
968
969 const size_t cNameServers = aNameServers.size();
970 if (cNameServers == 0)
971 return NULL;
972
973 const char **ppcszNameServers =
974 (const char **)RTMemAllocZ(sizeof(char *) * (cNameServers + 1));
975 if (ppcszNameServers == NULL)
976 return NULL;
977
978 size_t idxLast = 0;
979 for (size_t i = 0; i < cNameServers; ++i)
980 {
981 com::Utf8Str strNameServer(aNameServers[i]);
982 ppcszNameServers[idxLast] = RTStrDup(strNameServer.c_str());
983 if (ppcszNameServers[idxLast] != NULL)
984 ++idxLast;
985 }
986
987 if (idxLast == 0)
988 {
989 RTMemFree(ppcszNameServers);
990 return NULL;
991 }
992
993 return ppcszNameServers;
994}
995
996
997int VBoxNetLwipNAT::parseOpt(int rc, const RTGETOPTUNION& Val)
998{
999 switch (rc)
1000 {
1001 case 'p':
1002 case 'P':
1003 {
1004 NATSEVICEPORTFORWARDRULE Rule;
1005 VECNATSERVICEPF& rules = (rc == 'P'?
1006 m_vecPortForwardRule6
1007 : m_vecPortForwardRule4);
1008
1009 fDontLoadRulesOnStartup = true;
1010
1011 RT_ZERO(Rule);
1012
1013 int rc2 = netPfStrToPf(Val.psz, (rc == 'P'), &Rule.Pfr);
1014 RT_NOREF_PV(rc2);
1015 rules.push_back(Rule);
1016 return VINF_SUCCESS;
1017 }
1018 default:;
1019 }
1020 return VERR_NOT_FOUND;
1021}
1022
1023
1024int VBoxNetLwipNAT::processFrame(void *pvFrame, size_t cbFrame)
1025{
1026 AssertPtrReturn(pvFrame, VERR_INVALID_PARAMETER);
1027 AssertReturn(cbFrame != 0, VERR_INVALID_PARAMETER);
1028
1029 struct pbuf *p = pbuf_alloc(PBUF_RAW, (u16_t)cbFrame + ETH_PAD_SIZE, PBUF_POOL);
1030 if (RT_UNLIKELY(p == NULL))
1031 return VERR_NO_MEMORY;
1032
1033 /*
1034 * The code below is inlined version of:
1035 *
1036 * pbuf_header(p, -ETH_PAD_SIZE); // hide padding
1037 * pbuf_take(p, pvFrame, cbFrame);
1038 * pbuf_header(p, ETH_PAD_SIZE); // reveal padding
1039 */
1040 struct pbuf *q = p;
1041 uint8_t *pu8Chunk = (uint8_t *)pvFrame;
1042 do {
1043 uint8_t *payload = (uint8_t *)q->payload;
1044 size_t len = q->len;
1045
1046#if ETH_PAD_SIZE
1047 if (RT_LIKELY(q == p)) // single pbuf is large enough
1048 {
1049 payload += ETH_PAD_SIZE;
1050 len -= ETH_PAD_SIZE;
1051 }
1052#endif
1053 memcpy(payload, pu8Chunk, len);
1054 pu8Chunk += len;
1055 q = q->next;
1056 } while (RT_UNLIKELY(q != NULL));
1057
1058 m_LwipNetIf.input(p, &m_LwipNetIf);
1059 return VINF_SUCCESS;
1060}
1061
1062
1063int VBoxNetLwipNAT::processGSO(PCPDMNETWORKGSO pGso, size_t cbFrame)
1064{
1065 if (!PDMNetGsoIsValid(pGso, cbFrame, cbFrame - sizeof(PDMNETWORKGSO)))
1066 return VERR_INVALID_PARAMETER;
1067
1068 cbFrame -= sizeof(PDMNETWORKGSO);
1069 uint8_t abHdrScratch[256];
1070 uint32_t const cSegs = PDMNetGsoCalcSegmentCount(pGso,
1071 cbFrame);
1072 for (uint32_t iSeg = 0; iSeg < cSegs; iSeg++)
1073 {
1074 uint32_t cbSegFrame;
1075 void *pvSegFrame = PDMNetGsoCarveSegmentQD(pGso,
1076 (uint8_t *)(pGso + 1),
1077 cbFrame,
1078 abHdrScratch,
1079 iSeg,
1080 cSegs,
1081 &cbSegFrame);
1082
1083 int rc = processFrame(pvSegFrame, cbSegFrame);
1084 if (RT_FAILURE(rc))
1085 {
1086 return rc;
1087 }
1088 }
1089
1090 return VINF_SUCCESS;
1091}
1092
1093
1094int VBoxNetLwipNAT::run()
1095{
1096 /* Father starts receiving thread and enter event loop. */
1097 VBoxNetBaseService::run();
1098
1099 vboxLwipCoreFinalize(VBoxNetLwipNAT::onLwipTcpIpFini, this);
1100
1101 m_vecPortForwardRule4.clear();
1102 m_vecPortForwardRule6.clear();
1103
1104 destroyNatListener(m_NatListener, virtualbox);
1105 destroyNatListener(m_VBoxListener, virtualbox);
1106 destroyClientListener(m_VBoxClientListener, virtualboxClient);
1107
1108 return VINF_SUCCESS;
1109}
1110
1111
1112/**
1113 * Entry point.
1114 */
1115extern "C" DECLEXPORT(int) TrustedMain(int argc, char **argv, char **envp)
1116{
1117 int rc;
1118
1119 LogFlowFuncEnter();
1120
1121 NOREF(envp);
1122
1123#ifdef RT_OS_WINDOWS
1124 WSADATA wsaData;
1125 int err;
1126
1127 err = WSAStartup(MAKEWORD(2,2), &wsaData);
1128 if (err)
1129 {
1130 fprintf(stderr, "wsastartup: failed (%d)\n", err);
1131 return 1;
1132 }
1133#endif
1134
1135 SOCKET icmpsock4 = INVALID_SOCKET;
1136 SOCKET icmpsock6 = INVALID_SOCKET;
1137#ifndef RT_OS_DARWIN
1138 const int icmpstype = SOCK_RAW;
1139#else
1140 /* on OS X it's not privileged */
1141 const int icmpstype = SOCK_DGRAM;
1142#endif
1143
1144 icmpsock4 = socket(AF_INET, icmpstype, IPPROTO_ICMP);
1145 if (icmpsock4 == INVALID_SOCKET)
1146 {
1147 perror("IPPROTO_ICMP");
1148#ifdef VBOX_RAWSOCK_DEBUG_HELPER
1149 icmpsock4 = getrawsock(AF_INET);
1150#endif
1151 }
1152
1153 if (icmpsock4 != INVALID_SOCKET)
1154 {
1155#ifdef ICMP_FILTER // Linux specific
1156 struct icmp_filter flt = {
1157 ~(uint32_t)(
1158 (1U << ICMP_ECHOREPLY)
1159 | (1U << ICMP_DEST_UNREACH)
1160 | (1U << ICMP_TIME_EXCEEDED)
1161 )
1162 };
1163
1164 int status = setsockopt(icmpsock4, SOL_RAW, ICMP_FILTER,
1165 &flt, sizeof(flt));
1166 if (status < 0)
1167 {
1168 perror("ICMP_FILTER");
1169 }
1170#endif
1171 }
1172
1173 icmpsock6 = socket(AF_INET6, icmpstype, IPPROTO_ICMPV6);
1174 if (icmpsock6 == INVALID_SOCKET)
1175 {
1176 perror("IPPROTO_ICMPV6");
1177#ifdef VBOX_RAWSOCK_DEBUG_HELPER
1178 icmpsock6 = getrawsock(AF_INET6);
1179#endif
1180 }
1181
1182 if (icmpsock6 != INVALID_SOCKET)
1183 {
1184#ifdef ICMP6_FILTER // Windows doesn't support RFC 3542 API
1185 /*
1186 * XXX: We do this here for now, not in pxping.c, to avoid
1187 * name clashes between lwIP and system headers.
1188 */
1189 struct icmp6_filter flt;
1190 ICMP6_FILTER_SETBLOCKALL(&flt);
1191
1192 ICMP6_FILTER_SETPASS(ICMP6_ECHO_REPLY, &flt);
1193
1194 ICMP6_FILTER_SETPASS(ICMP6_DST_UNREACH, &flt);
1195 ICMP6_FILTER_SETPASS(ICMP6_PACKET_TOO_BIG, &flt);
1196 ICMP6_FILTER_SETPASS(ICMP6_TIME_EXCEEDED, &flt);
1197 ICMP6_FILTER_SETPASS(ICMP6_PARAM_PROB, &flt);
1198
1199 int status = setsockopt(icmpsock6, IPPROTO_ICMPV6, ICMP6_FILTER,
1200 &flt, sizeof(flt));
1201 if (status < 0)
1202 {
1203 perror("ICMP6_FILTER");
1204 }
1205#endif
1206 }
1207
1208 HRESULT hrc = com::Initialize();
1209 if (FAILED(hrc))
1210 {
1211#ifdef VBOX_WITH_XPCOM
1212 if (hrc == NS_ERROR_FILE_ACCESS_DENIED)
1213 {
1214 char szHome[RTPATH_MAX] = "";
1215 int vrc = com::GetVBoxUserHomeDirectory(szHome, sizeof(szHome), false);
1216 if (RT_SUCCESS(vrc))
1217 {
1218 closesocket(icmpsock4);
1219 closesocket(icmpsock6);
1220 return RTMsgErrorExit(RTEXITCODE_FAILURE,
1221 "Failed to initialize COM: %s: %Rhrf",
1222 szHome, hrc);
1223 }
1224 }
1225#endif // VBOX_WITH_XPCOM
1226 closesocket(icmpsock4);
1227 closesocket(icmpsock6);
1228 return RTMsgErrorExit(RTEXITCODE_FAILURE,
1229 "Failed to initialize COM: %Rhrf", hrc);
1230 }
1231
1232 rc = vboxNetNATLogInit(argc, argv);
1233 // shall we bail if we failed to init logging?
1234
1235 g_pLwipNat = new VBoxNetLwipNAT(icmpsock4, icmpsock6);
1236
1237 Log2(("NAT: initialization\n"));
1238 rc = g_pLwipNat->parseArgs(argc - 1, argv + 1);
1239 rc = (rc == 0) ? VINF_SUCCESS : VERR_GENERAL_FAILURE; /* XXX: FIXME */
1240
1241 if (RT_SUCCESS(rc))
1242 rc = g_pLwipNat->init();
1243
1244 if (RT_SUCCESS(rc))
1245 g_pLwipNat->run();
1246
1247 delete g_pLwipNat;
1248 return 0;
1249}
1250
1251
1252static int vboxNetNATLogInit(int argc, char **argv)
1253{
1254 size_t cch;
1255 int rc;
1256
1257 char szHome[RTPATH_MAX];
1258 rc = com::GetVBoxUserHomeDirectory(szHome, sizeof(szHome), false);
1259 if (RT_FAILURE(rc))
1260 return rc;
1261
1262 const char *pcszNetwork = NULL;
1263
1264 // XXX: This duplicates information from VBoxNetBaseService.cpp.
1265 // Perhaps option definitions should be exported as public static
1266 // member of VBoxNetBaseService?
1267 static const RTGETOPTDEF s_aOptions[] = {
1268 { "--network", 'n', RTGETOPT_REQ_STRING }
1269 };
1270
1271 RTGETOPTSTATE GetState;
1272 RTGetOptInit(&GetState, argc, argv, s_aOptions, RT_ELEMENTS(s_aOptions), 1,
1273 RTGETOPTINIT_FLAGS_NO_STD_OPTS);
1274
1275 RTGETOPTUNION ValueUnion;
1276 int ch;
1277 while ((ch = RTGetOpt(&GetState, &ValueUnion)))
1278 {
1279 if (ch == 'n')
1280 {
1281 pcszNetwork = ValueUnion.psz;
1282 break;
1283 }
1284 }
1285
1286 if (pcszNetwork == NULL)
1287 return VERR_MISSING;
1288
1289 char szNetwork[RTPATH_MAX];
1290 rc = RTStrCopy(szNetwork, sizeof(szNetwork), pcszNetwork);
1291 if (RT_FAILURE(rc))
1292 return rc;
1293
1294 // sanitize network name to be usable as a path component
1295 for (char *p = szNetwork; *p != '\0'; ++p)
1296 {
1297 if (RTPATH_IS_SEP(*p))
1298 *p = '_';
1299 }
1300
1301 char szLogFile[RTPATH_MAX];
1302 cch = RTStrPrintf(szLogFile, sizeof(szLogFile),
1303 "%s%c%s.log", szHome, RTPATH_DELIMITER, szNetwork);
1304 if (cch >= sizeof(szLogFile))
1305 {
1306 return VERR_BUFFER_OVERFLOW;
1307 }
1308
1309 // sanitize network name some more to be usable as environment variable
1310 for (char *p = szNetwork; *p != '\0'; ++p)
1311 {
1312 if (*p != '_'
1313 && (*p < '0' || '9' < *p)
1314 && (*p < 'a' || 'z' < *p)
1315 && (*p < 'A' || 'Z' < *p))
1316 {
1317 *p = '_';
1318 }
1319 }
1320
1321 char szEnvVarBase[128];
1322 cch = RTStrPrintf(szEnvVarBase, sizeof(szEnvVarBase),
1323 "VBOXNET_%s_RELEASE_LOG", szNetwork);
1324 if (cch >= sizeof(szEnvVarBase))
1325 return VERR_BUFFER_OVERFLOW;
1326
1327 rc = com::VBoxLogRelCreate("NAT Network",
1328 szLogFile,
1329 RTLOGFLAGS_PREFIX_TIME_PROG,
1330 "all all.restrict -default.restrict",
1331 szEnvVarBase,
1332 RTLOGDEST_FILE,
1333 32768 /* cMaxEntriesPerGroup */,
1334 0 /* cHistory */,
1335 0 /* uHistoryFileTime */,
1336 0 /* uHistoryFileSize */,
1337 NULL /*pErrInfo*/);
1338
1339 /*
1340 * Provide immediate feedback if corresponding LogRel level is
1341 * enabled. It's frustrating when you chase some rare event and
1342 * discover you didn't actually have the corresponding log level
1343 * enabled because of a typo in the environment variable name or
1344 * its content.
1345 */
1346#define LOG_PING(_log) _log((#_log " enabled\n"))
1347 LOG_PING(LogRel2);
1348 LOG_PING(LogRel3);
1349 LOG_PING(LogRel4);
1350 LOG_PING(LogRel5);
1351 LOG_PING(LogRel6);
1352 LOG_PING(LogRel7);
1353 LOG_PING(LogRel8);
1354 LOG_PING(LogRel9);
1355 LOG_PING(LogRel10);
1356 LOG_PING(LogRel11);
1357 LOG_PING(LogRel12);
1358
1359 return rc;
1360}
1361
1362
1363static int fetchNatPortForwardRules(const ComNatPtr& nat, bool fIsIPv6, VECNATSERVICEPF& vec)
1364{
1365 HRESULT hrc;
1366 com::SafeArray<BSTR> rules;
1367 if (fIsIPv6)
1368 hrc = nat->COMGETTER(PortForwardRules6)(ComSafeArrayAsOutParam(rules));
1369 else
1370 hrc = nat->COMGETTER(PortForwardRules4)(ComSafeArrayAsOutParam(rules));
1371 AssertComRCReturn(hrc, VERR_INTERNAL_ERROR);
1372
1373 NATSEVICEPORTFORWARDRULE Rule;
1374 for (size_t idxRules = 0; idxRules < rules.size(); ++idxRules)
1375 {
1376 Log(("%d-%s rule: %ls\n", idxRules, (fIsIPv6 ? "IPv6" : "IPv4"), rules[idxRules]));
1377 RT_ZERO(Rule);
1378
1379 int rc = netPfStrToPf(com::Utf8Str(rules[idxRules]).c_str(), fIsIPv6,
1380 &Rule.Pfr);
1381 if (RT_FAILURE(rc))
1382 continue;
1383
1384 vec.push_back(Rule);
1385 }
1386
1387 return VINF_SUCCESS;
1388}
1389
1390
1391#ifndef VBOX_WITH_HARDENING
1392
1393int main(int argc, char **argv, char **envp)
1394{
1395 int rc = RTR3InitExe(argc, &argv, RTR3INIT_FLAGS_SUPLIB);
1396 if (RT_FAILURE(rc))
1397 return RTMsgInitFailure(rc);
1398
1399 return TrustedMain(argc, argv, envp);
1400}
1401
1402# if defined(RT_OS_WINDOWS)
1403
1404# if 0 /* Some copy and paste from DHCP that nobody explained why was diabled. */
1405static LRESULT CALLBACK WindowProc(HWND hwnd,
1406 UINT uMsg,
1407 WPARAM wParam,
1408 LPARAM lParam
1409)
1410{
1411 if(uMsg == WM_DESTROY)
1412 {
1413 PostQuitMessage(0);
1414 return 0;
1415 }
1416 return DefWindowProc (hwnd, uMsg, wParam, lParam);
1417}
1418
1419static LPCWSTR g_WndClassName = L"VBoxNetNatLwipClass";
1420
1421static DWORD WINAPI MsgThreadProc(__in LPVOID lpParameter)
1422{
1423 HWND hwnd = 0;
1424 HINSTANCE hInstance = (HINSTANCE)GetModuleHandle (NULL);
1425 bool bExit = false;
1426
1427 /* Register the Window Class. */
1428 WNDCLASS wc;
1429 wc.style = 0;
1430 wc.lpfnWndProc = WindowProc;
1431 wc.cbClsExtra = 0;
1432 wc.cbWndExtra = sizeof(void *);
1433 wc.hInstance = hInstance;
1434 wc.hIcon = NULL;
1435 wc.hCursor = NULL;
1436 wc.hbrBackground = (HBRUSH)(COLOR_BACKGROUND + 1);
1437 wc.lpszMenuName = NULL;
1438 wc.lpszClassName = g_WndClassName;
1439
1440 ATOM atomWindowClass = RegisterClass(&wc);
1441
1442 if (atomWindowClass != 0)
1443 {
1444 /* Create the window. */
1445 hwnd = CreateWindowEx(WS_EX_TOOLWINDOW | WS_EX_TRANSPARENT | WS_EX_TOPMOST,
1446 g_WndClassName, g_WndClassName, WS_POPUPWINDOW,
1447 -200, -200, 100, 100, NULL, NULL, hInstance, NULL);
1448
1449 if (hwnd)
1450 {
1451 SetWindowPos(hwnd, HWND_TOPMOST, -200, -200, 0, 0,
1452 SWP_NOACTIVATE | SWP_HIDEWINDOW | SWP_NOCOPYBITS | SWP_NOREDRAW | SWP_NOSIZE);
1453
1454 MSG msg;
1455 while (GetMessage(&msg, NULL, 0, 0))
1456 {
1457 TranslateMessage(&msg);
1458 DispatchMessage(&msg);
1459 }
1460
1461 DestroyWindow (hwnd);
1462
1463 bExit = true;
1464 }
1465
1466 UnregisterClass (g_WndClassName, hInstance);
1467 }
1468
1469 if(bExit)
1470 {
1471 /* no need any accuracy here, in anyway the DHCP server usually gets terminated with TerminateProcess */
1472 exit(0);
1473 }
1474
1475 return 0;
1476}
1477# endif
1478
1479
1480/** (We don't want a console usually.) */
1481int WINAPI WinMain(HINSTANCE hInstance, HINSTANCE hPrevInstance, LPSTR lpCmdLine, int nCmdShow)
1482{
1483 RT_NOREF(hInstance, hPrevInstance, lpCmdLine, nCmdShow);
1484# if 0 /* some copy and paste from DHCP that nobody explained why was diabled. */
1485 NOREF(hInstance); NOREF(hPrevInstance); NOREF(lpCmdLine); NOREF(nCmdShow);
1486
1487 HANDLE hThread = CreateThread(
1488 NULL, /*__in_opt LPSECURITY_ATTRIBUTES lpThreadAttributes, */
1489 0, /*__in SIZE_T dwStackSize, */
1490 MsgThreadProc, /*__in LPTHREAD_START_ROUTINE lpStartAddress,*/
1491 NULL, /*__in_opt LPVOID lpParameter,*/
1492 0, /*__in DWORD dwCreationFlags,*/
1493 NULL /*__out_opt LPDWORD lpThreadId*/
1494 );
1495
1496 if(hThread != NULL)
1497 CloseHandle(hThread);
1498
1499# endif
1500 return main(__argc, __argv, environ);
1501}
1502# endif /* RT_OS_WINDOWS */
1503
1504#endif /* !VBOX_WITH_HARDENING */
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