VirtualBox

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

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

NAT/Net: In various callback functions consistently use the callback
cookie to access the VBoxNetLwipNAT object - not the wild and
confusing mixture of both the cookie and the global singleton
variable. Consistently call it "self". No functional change
intended.

  • 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 87375 2021-01-22 18:26:45Z 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 *self = 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 = self->getIpv4Address();
441 RTNETADDRIPV4 netmask = self->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(&self->m_LwipNetIf /* Lwip Interface */,
451 &LwipIpAddr /* IP address*/,
452 &LwipIpNetMask /* Network mask */,
453 &LwipIpAddr /* gateway address, @todo: is self IP acceptable? */,
454 self /* 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 (self->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(&self->m_LwipNetIf, &self->m_ProxyOptions);
511
512 natServiceProcessRegisteredPf(self->m_vecPortForwardRule4);
513 natServiceProcessRegisteredPf(self->m_vecPortForwardRule6);
514}
515
516
517/*static*/ DECLCALLBACK(void) VBoxNetLwipNAT::onLwipTcpIpFini(void* arg)
518{
519 AssertPtrReturnVoid(arg);
520 VBoxNetLwipNAT *self = static_cast<VBoxNetLwipNAT *>(arg);
521
522 /* XXX: proxy finalization */
523 netif_set_link_down(&self->m_LwipNetIf);
524 netif_set_down(&self->m_LwipNetIf);
525 netif_remove(&self->m_LwipNetIf);
526
527}
528
529/*
530 * Callback for netif_add() to initialize the interface.
531 */
532/*static*/ err_t VBoxNetLwipNAT::netifInit(netif *pNetif) RT_NOTHROW_DEF
533{
534 err_t rcLwip = ERR_OK;
535
536 AssertPtrReturn(pNetif, ERR_ARG);
537
538 VBoxNetLwipNAT *self = static_cast<VBoxNetLwipNAT *>(pNetif->state);
539 AssertPtrReturn(self, ERR_ARG);
540
541 LogFlowFunc(("ENTER: pNetif[%c%c%d]\n", pNetif->name[0], pNetif->name[1], pNetif->num));
542 /* validity */
543 AssertReturn( pNetif->name[0] == 'N'
544 && pNetif->name[1] == 'T', ERR_ARG);
545
546
547 pNetif->hwaddr_len = sizeof(RTMAC);
548 RTMAC mac = self->getMacAddress();
549 memcpy(pNetif->hwaddr, &mac, sizeof(RTMAC));
550
551 self->m_u16Mtu = 1500; // XXX: FIXME
552 pNetif->mtu = self->m_u16Mtu;
553
554 pNetif->flags = NETIF_FLAG_BROADCAST
555 | NETIF_FLAG_ETHARP /* Don't bother driver with ARP and let Lwip resolve ARP handling */
556 | NETIF_FLAG_ETHERNET; /* Lwip works with ethernet too */
557
558 pNetif->linkoutput = netifLinkoutput; /* ether-level-pipe */
559 pNetif->output = etharp_output; /* ip-pipe */
560
561 if (self->m_ProxyOptions.ipv6_enabled) {
562 pNetif->output_ip6 = ethip6_output;
563
564 /* IPv6 link-local address in slot 0 */
565 netif_create_ip6_linklocal_address(pNetif, /* :from_mac_48bit */ 1);
566 netif_ip6_addr_set_state(pNetif, 0, IP6_ADDR_PREFERRED); // skip DAD
567
568 /*
569 * RFC 4193 Locally Assigned Global ID (ULA) in slot 1
570 * [fd17:625c:f037:XXXX::1] where XXXX, 16 bit Subnet ID, are two
571 * bytes from the middle of the IPv4 address, e.g. :dead: for
572 * 10.222.173.1
573 */
574 u8_t nethi = ip4_addr2(&pNetif->ip_addr);
575 u8_t netlo = ip4_addr3(&pNetif->ip_addr);
576
577 ip6_addr_t *paddr = netif_ip6_addr(pNetif, 1);
578 IP6_ADDR(paddr, 0, 0xFD, 0x17, 0x62, 0x5C);
579 IP6_ADDR(paddr, 1, 0xF0, 0x37, nethi, netlo);
580 IP6_ADDR(paddr, 2, 0x00, 0x00, 0x00, 0x00);
581 IP6_ADDR(paddr, 3, 0x00, 0x00, 0x00, 0x01);
582 netif_ip6_addr_set_state(pNetif, 1, IP6_ADDR_PREFERRED);
583
584#if LWIP_IPV6_SEND_ROUTER_SOLICIT
585 pNetif->rs_count = 0;
586#endif
587 }
588
589 LogFlowFunc(("LEAVE: %d\n", rcLwip));
590 return rcLwip;
591}
592
593
594/*static*/ err_t VBoxNetLwipNAT::netifLinkoutput(netif *pNetif, pbuf *pPBuf) RT_NOTHROW_DEF
595{
596 AssertPtrReturn(pNetif, ERR_ARG);
597 AssertPtrReturn(pPBuf, ERR_ARG);
598
599 VBoxNetLwipNAT *self = static_cast<VBoxNetLwipNAT *>(pNetif->state);
600 AssertPtrReturn(self, ERR_IF);
601 AssertReturn(self == g_pLwipNat, ERR_ARG);
602
603 LogFlowFunc(("ENTER: pNetif[%c%c%d], pPbuf:%p\n",
604 pNetif->name[0],
605 pNetif->name[1],
606 pNetif->num,
607 pPBuf));
608
609 RT_ZERO(VBoxNetLwipNAT::aXmitSeg);
610
611 size_t idx = 0;
612 for (struct pbuf *q = pPBuf; q != NULL; q = q->next, ++idx)
613 {
614 AssertReturn(idx < RT_ELEMENTS(VBoxNetLwipNAT::aXmitSeg), ERR_MEM);
615
616#if ETH_PAD_SIZE
617 if (q == pPBuf)
618 {
619 VBoxNetLwipNAT::aXmitSeg[idx].pv = (uint8_t *)q->payload + ETH_PAD_SIZE;
620 VBoxNetLwipNAT::aXmitSeg[idx].cb = q->len - ETH_PAD_SIZE;
621 }
622 else
623#endif
624 {
625 VBoxNetLwipNAT::aXmitSeg[idx].pv = q->payload;
626 VBoxNetLwipNAT::aXmitSeg[idx].cb = q->len;
627 }
628 }
629
630 int rc = self->sendBufferOnWire(VBoxNetLwipNAT::aXmitSeg, idx,
631 pPBuf->tot_len - ETH_PAD_SIZE);
632 AssertRCReturn(rc, ERR_IF);
633
634 self->flushWire();
635
636 LogFlowFunc(("LEAVE: %d\n", ERR_OK));
637 return ERR_OK;
638}
639
640
641VBoxNetLwipNAT::VBoxNetLwipNAT(SOCKET icmpsock4, SOCKET icmpsock6) : VBoxNetBaseService("VBoxNetNAT", "nat-network")
642{
643 LogFlowFuncEnter();
644
645 m_ProxyOptions.ipv6_enabled = 0;
646 m_ProxyOptions.ipv6_defroute = 0;
647 m_ProxyOptions.icmpsock4 = icmpsock4;
648 m_ProxyOptions.icmpsock6 = icmpsock6;
649 m_ProxyOptions.tftp_root = NULL;
650 m_ProxyOptions.src4 = NULL;
651 m_ProxyOptions.src6 = NULL;
652 RT_ZERO(m_src4);
653 RT_ZERO(m_src6);
654 m_src4.sin_family = AF_INET;
655 m_src6.sin6_family = AF_INET6;
656#if HAVE_SA_LEN
657 m_src4.sin_len = sizeof(m_src4);
658 m_src6.sin6_len = sizeof(m_src6);
659#endif
660 m_ProxyOptions.nameservers = NULL;
661
662 m_LwipNetIf.name[0] = 'N';
663 m_LwipNetIf.name[1] = 'T';
664
665 RTMAC mac;
666 mac.au8[0] = 0x52;
667 mac.au8[1] = 0x54;
668 mac.au8[2] = 0;
669 mac.au8[3] = 0x12;
670 mac.au8[4] = 0x35;
671 mac.au8[5] = 0;
672 setMacAddress(mac);
673
674 RTNETADDRIPV4 address;
675 address.u = RT_MAKE_U32_FROM_U8( 10, 0, 2, 2); // NB: big-endian
676 setIpv4Address(address);
677
678 address.u = RT_H2N_U32_C(0xffffff00);
679 setIpv4Netmask(address);
680
681 fDontLoadRulesOnStartup = false;
682
683 for(unsigned int i = 0; i < RT_ELEMENTS(g_aGetOptDef); ++i)
684 addCommandLineOption(&g_aGetOptDef[i]);
685
686 LogFlowFuncLeave();
687}
688
689
690VBoxNetLwipNAT::~VBoxNetLwipNAT()
691{
692 if (m_ProxyOptions.tftp_root)
693 {
694 RTStrFree((char *)m_ProxyOptions.tftp_root);
695 m_ProxyOptions.tftp_root = NULL;
696 }
697 if (m_ProxyOptions.nameservers)
698 {
699 const char **pv = m_ProxyOptions.nameservers;
700 while (*pv)
701 {
702 RTStrFree((char*)*pv);
703 pv++;
704 }
705 RTMemFree(m_ProxyOptions.nameservers);
706 m_ProxyOptions.nameservers = NULL;
707 }
708}
709
710
711/*static*/ int VBoxNetLwipNAT::natServicePfRegister(NATSEVICEPORTFORWARDRULE& natPf)
712{
713 int lrc;
714
715 int sockFamily = (natPf.Pfr.fPfrIPv6 ? PF_INET6 : PF_INET);
716 int socketSpec;
717 switch(natPf.Pfr.iPfrProto)
718 {
719 case IPPROTO_TCP:
720 socketSpec = SOCK_STREAM;
721 break;
722 case IPPROTO_UDP:
723 socketSpec = SOCK_DGRAM;
724 break;
725 default:
726 return VERR_IGNORED;
727 }
728
729 const char *pszHostAddr = natPf.Pfr.szPfrHostAddr;
730 if (pszHostAddr[0] == '\0')
731 {
732 if (sockFamily == PF_INET)
733 pszHostAddr = "0.0.0.0";
734 else
735 pszHostAddr = "::";
736 }
737
738 lrc = fwspec_set(&natPf.FWSpec,
739 sockFamily,
740 socketSpec,
741 pszHostAddr,
742 natPf.Pfr.u16PfrHostPort,
743 natPf.Pfr.szPfrGuestAddr,
744 natPf.Pfr.u16PfrGuestPort);
745 if (lrc != 0)
746 return VERR_IGNORED;
747
748 fwspec *pFwCopy = (fwspec *)RTMemDup(&natPf.FWSpec, sizeof(natPf.FWSpec));
749 if (pFwCopy)
750 {
751 lrc = portfwd_rule_add(pFwCopy);
752 if (lrc == 0)
753 return VINF_SUCCESS; /* (pFwCopy is owned by lwip thread now.) */
754 RTMemFree(pFwCopy);
755 }
756 else
757 LogRel(("Unable to allocate memory for %s rule \"%s\"\n",
758 natPf.Pfr.fPfrIPv6 ? "IPv6" : "IPv4",
759 natPf.Pfr.szPfrName));
760 return VERR_IGNORED;
761}
762
763
764/*static*/ int VBoxNetLwipNAT::natServiceProcessRegisteredPf(VECNATSERVICEPF& vecRules)
765{
766 ITERATORNATSERVICEPF it;
767 for (it = vecRules.begin(); it != vecRules.end(); ++it)
768 {
769 NATSEVICEPORTFORWARDRULE &natPf = *it;
770
771 LogRel(("Loading %s port-forwarding rule \"%s\": %s %s%s%s:%d -> %s%s%s:%d\n",
772 natPf.Pfr.fPfrIPv6 ? "IPv6" : "IPv4",
773 natPf.Pfr.szPfrName,
774 natPf.Pfr.iPfrProto == IPPROTO_TCP ? "TCP" : "UDP",
775 /* from */
776 natPf.Pfr.fPfrIPv6 ? "[" : "",
777 natPf.Pfr.szPfrHostAddr,
778 natPf.Pfr.fPfrIPv6 ? "]" : "",
779 natPf.Pfr.u16PfrHostPort,
780 /* to */
781 natPf.Pfr.fPfrIPv6 ? "[" : "",
782 natPf.Pfr.szPfrGuestAddr,
783 natPf.Pfr.fPfrIPv6 ? "]" : "",
784 natPf.Pfr.u16PfrGuestPort));
785
786 natServicePfRegister(natPf);
787 }
788
789 return VINF_SUCCESS;
790}
791
792
793/**
794 * Main thread. Starts also the LWIP thread.
795 */
796int VBoxNetLwipNAT::init()
797{
798 LogFlowFuncEnter();
799
800 /* virtualbox initialized in super class */
801 int rc = ::VBoxNetBaseService::init();
802 AssertRCReturn(rc, rc);
803
804 std::string networkName = getNetworkName();
805 rc = findNatNetwork(virtualbox, networkName, m_net);
806 AssertRCReturn(rc, rc);
807
808 {
809 ComEventTypeArray eventTypes;
810 eventTypes.push_back(VBoxEventType_OnNATNetworkPortForward);
811 eventTypes.push_back(VBoxEventType_OnNATNetworkSetting);
812 rc = createNatListener(m_NatListener, virtualbox, this, eventTypes);
813 AssertRCReturn(rc, rc);
814 }
815
816
817 // resolver changes are reported on vbox but are retrieved from
818 // host so stash a pointer for future lookups
819 HRESULT hrc = virtualbox->COMGETTER(Host)(m_host.asOutParam());
820 AssertComRCReturn(hrc, VERR_INTERNAL_ERROR);
821
822 {
823 ComEventTypeArray eventTypes;
824 eventTypes.push_back(VBoxEventType_OnHostNameResolutionConfigurationChange);
825 eventTypes.push_back(VBoxEventType_OnNATNetworkStartStop);
826 rc = createNatListener(m_VBoxListener, virtualbox, this, eventTypes);
827 AssertRCReturn(rc, rc);
828 }
829
830 {
831 ComEventTypeArray eventTypes;
832 eventTypes.push_back(VBoxEventType_OnVBoxSVCAvailabilityChanged);
833 rc = createClientListener(m_VBoxClientListener, virtualboxClient, this, eventTypes);
834 AssertRCReturn(rc, rc);
835 }
836
837 BOOL fIPv6Enabled = FALSE;
838 hrc = m_net->COMGETTER(IPv6Enabled)(&fIPv6Enabled);
839 AssertComRCReturn(hrc, VERR_NOT_FOUND);
840
841 BOOL fIPv6DefaultRoute = FALSE;
842 if (fIPv6Enabled)
843 {
844 hrc = m_net->COMGETTER(AdvertiseDefaultIPv6RouteEnabled)(&fIPv6DefaultRoute);
845 AssertComRCReturn(hrc, VERR_NOT_FOUND);
846 }
847
848 m_ProxyOptions.ipv6_enabled = fIPv6Enabled;
849 m_ProxyOptions.ipv6_defroute = fIPv6DefaultRoute;
850
851
852 /*
853 * Bind outgoing connections to the specified IP.
854 */
855 com::Bstr bstrSourceIpX;
856
857 /* IPv4 */
858 com::Bstr bstrSourceIp4Key = com::BstrFmt("NAT/%s/SourceIp4", networkName.c_str());
859 hrc = virtualbox->GetExtraData(bstrSourceIp4Key.raw(), bstrSourceIpX.asOutParam());
860 if (SUCCEEDED(hrc) && bstrSourceIpX.isNotEmpty())
861 {
862 RTNETADDRIPV4 addr;
863 rc = RTNetStrToIPv4Addr(com::Utf8Str(bstrSourceIpX).c_str(), &addr);
864 if (RT_SUCCESS(rc))
865 {
866 m_src4.sin_addr.s_addr = addr.u;
867 m_ProxyOptions.src4 = &m_src4;
868
869 LogRel(("Will use %RTnaipv4 as IPv4 source address\n",
870 m_src4.sin_addr.s_addr));
871 }
872 else
873 {
874 LogRel(("Failed to parse \"%s\" IPv4 source address specification\n",
875 com::Utf8Str(bstrSourceIpX).c_str()));
876 }
877
878 bstrSourceIpX.setNull();
879 }
880
881 /* IPv6 */
882 com::Bstr bstrSourceIp6Key = com::BstrFmt("NAT/%s/SourceIp6", networkName.c_str());
883 hrc = virtualbox->GetExtraData(bstrSourceIp6Key.raw(), bstrSourceIpX.asOutParam());
884 if (SUCCEEDED(hrc) && bstrSourceIpX.isNotEmpty())
885 {
886 RTNETADDRIPV6 addr;
887 char *pszZone = NULL;
888 rc = RTNetStrToIPv6Addr(com::Utf8Str(bstrSourceIpX).c_str(), &addr, &pszZone);
889 if (RT_SUCCESS(rc))
890 {
891 memcpy(&m_src6.sin6_addr, &addr, sizeof(addr));
892 m_ProxyOptions.src6 = &m_src6;
893
894 LogRel(("Will use %RTnaipv6 as IPv6 source address\n",
895 &m_src6.sin6_addr));
896 }
897 else
898 {
899 LogRel(("Failed to parse \"%s\" IPv6 source address specification\n",
900 com::Utf8Str(bstrSourceIpX).c_str()));
901 }
902
903 bstrSourceIpX.setNull();
904 }
905
906
907 if (!fDontLoadRulesOnStartup)
908 {
909 fetchNatPortForwardRules(m_net, false, m_vecPortForwardRule4);
910 fetchNatPortForwardRules(m_net, true, m_vecPortForwardRule6);
911 } /* if (!fDontLoadRulesOnStartup) */
912
913 AddressToOffsetMapping tmp;
914 rc = localMappings(m_net, tmp);
915 if (RT_SUCCESS(rc) && !tmp.empty())
916 {
917 unsigned long i = 0;
918 for (AddressToOffsetMapping::iterator it = tmp.begin();
919 it != tmp.end() && i < RT_ELEMENTS(m_lo2off);
920 ++it, ++i)
921 {
922 ip4_addr_set_u32(&m_lo2off[i].loaddr, it->first.u);
923 m_lo2off[i].off = it->second;
924 }
925
926 m_loOptDescriptor.lomap = m_lo2off;
927 m_loOptDescriptor.num_lomap = i;
928 m_ProxyOptions.lomap_desc = &m_loOptDescriptor;
929 }
930
931 com::Bstr bstr;
932 hrc = virtualbox->COMGETTER(HomeFolder)(bstr.asOutParam());
933 AssertComRCReturn(hrc, VERR_NOT_FOUND);
934 if (!bstr.isEmpty())
935 {
936 com::Utf8Str strTftpRoot(com::Utf8StrFmt("%ls%c%s",
937 bstr.raw(), RTPATH_DELIMITER, "TFTP"));
938 char *pszStrTemp; // avoid const char ** vs char **
939 rc = RTStrUtf8ToCurrentCP(&pszStrTemp, strTftpRoot.c_str());
940 AssertRC(rc);
941 m_ProxyOptions.tftp_root = pszStrTemp;
942 }
943
944 m_ProxyOptions.nameservers = getHostNameservers();
945
946 /* end of COM initialization */
947
948 rc = tryGoOnline();
949 if (RT_FAILURE(rc))
950 return rc;
951
952 /* this starts LWIP thread */
953 vboxLwipCoreInitialize(VBoxNetLwipNAT::onLwipTcpIpInit, this);
954
955 LogFlowFuncLeaveRC(rc);
956 return rc;
957}
958
959
960const char **VBoxNetLwipNAT::getHostNameservers()
961{
962 if (m_host.isNull())
963 return NULL;
964
965 com::SafeArray<BSTR> aNameServers;
966 HRESULT hrc = m_host->COMGETTER(NameServers)(ComSafeArrayAsOutParam(aNameServers));
967 if (FAILED(hrc))
968 return NULL;
969
970 const size_t cNameServers = aNameServers.size();
971 if (cNameServers == 0)
972 return NULL;
973
974 const char **ppcszNameServers =
975 (const char **)RTMemAllocZ(sizeof(char *) * (cNameServers + 1));
976 if (ppcszNameServers == NULL)
977 return NULL;
978
979 size_t idxLast = 0;
980 for (size_t i = 0; i < cNameServers; ++i)
981 {
982 com::Utf8Str strNameServer(aNameServers[i]);
983 ppcszNameServers[idxLast] = RTStrDup(strNameServer.c_str());
984 if (ppcszNameServers[idxLast] != NULL)
985 ++idxLast;
986 }
987
988 if (idxLast == 0)
989 {
990 RTMemFree(ppcszNameServers);
991 return NULL;
992 }
993
994 return ppcszNameServers;
995}
996
997
998int VBoxNetLwipNAT::parseOpt(int rc, const RTGETOPTUNION& Val)
999{
1000 switch (rc)
1001 {
1002 case 'p':
1003 case 'P':
1004 {
1005 NATSEVICEPORTFORWARDRULE Rule;
1006 VECNATSERVICEPF& rules = (rc == 'P'?
1007 m_vecPortForwardRule6
1008 : m_vecPortForwardRule4);
1009
1010 fDontLoadRulesOnStartup = true;
1011
1012 RT_ZERO(Rule);
1013
1014 int rc2 = netPfStrToPf(Val.psz, (rc == 'P'), &Rule.Pfr);
1015 RT_NOREF_PV(rc2);
1016 rules.push_back(Rule);
1017 return VINF_SUCCESS;
1018 }
1019 default:;
1020 }
1021 return VERR_NOT_FOUND;
1022}
1023
1024
1025int VBoxNetLwipNAT::processFrame(void *pvFrame, size_t cbFrame)
1026{
1027 AssertPtrReturn(pvFrame, VERR_INVALID_PARAMETER);
1028 AssertReturn(cbFrame != 0, VERR_INVALID_PARAMETER);
1029
1030 struct pbuf *p = pbuf_alloc(PBUF_RAW, (u16_t)cbFrame + ETH_PAD_SIZE, PBUF_POOL);
1031 if (RT_UNLIKELY(p == NULL))
1032 return VERR_NO_MEMORY;
1033
1034 /*
1035 * The code below is inlined version of:
1036 *
1037 * pbuf_header(p, -ETH_PAD_SIZE); // hide padding
1038 * pbuf_take(p, pvFrame, cbFrame);
1039 * pbuf_header(p, ETH_PAD_SIZE); // reveal padding
1040 */
1041 struct pbuf *q = p;
1042 uint8_t *pu8Chunk = (uint8_t *)pvFrame;
1043 do {
1044 uint8_t *payload = (uint8_t *)q->payload;
1045 size_t len = q->len;
1046
1047#if ETH_PAD_SIZE
1048 if (RT_LIKELY(q == p)) // single pbuf is large enough
1049 {
1050 payload += ETH_PAD_SIZE;
1051 len -= ETH_PAD_SIZE;
1052 }
1053#endif
1054 memcpy(payload, pu8Chunk, len);
1055 pu8Chunk += len;
1056 q = q->next;
1057 } while (RT_UNLIKELY(q != NULL));
1058
1059 m_LwipNetIf.input(p, &m_LwipNetIf);
1060 return VINF_SUCCESS;
1061}
1062
1063
1064int VBoxNetLwipNAT::processGSO(PCPDMNETWORKGSO pGso, size_t cbFrame)
1065{
1066 if (!PDMNetGsoIsValid(pGso, cbFrame, cbFrame - sizeof(PDMNETWORKGSO)))
1067 return VERR_INVALID_PARAMETER;
1068
1069 cbFrame -= sizeof(PDMNETWORKGSO);
1070 uint8_t abHdrScratch[256];
1071 uint32_t const cSegs = PDMNetGsoCalcSegmentCount(pGso,
1072 cbFrame);
1073 for (uint32_t iSeg = 0; iSeg < cSegs; iSeg++)
1074 {
1075 uint32_t cbSegFrame;
1076 void *pvSegFrame = PDMNetGsoCarveSegmentQD(pGso,
1077 (uint8_t *)(pGso + 1),
1078 cbFrame,
1079 abHdrScratch,
1080 iSeg,
1081 cSegs,
1082 &cbSegFrame);
1083
1084 int rc = processFrame(pvSegFrame, cbSegFrame);
1085 if (RT_FAILURE(rc))
1086 {
1087 return rc;
1088 }
1089 }
1090
1091 return VINF_SUCCESS;
1092}
1093
1094
1095int VBoxNetLwipNAT::run()
1096{
1097 /* Father starts receiving thread and enter event loop. */
1098 VBoxNetBaseService::run();
1099
1100 vboxLwipCoreFinalize(VBoxNetLwipNAT::onLwipTcpIpFini, this);
1101
1102 m_vecPortForwardRule4.clear();
1103 m_vecPortForwardRule6.clear();
1104
1105 destroyNatListener(m_NatListener, virtualbox);
1106 destroyNatListener(m_VBoxListener, virtualbox);
1107 destroyClientListener(m_VBoxClientListener, virtualboxClient);
1108
1109 return VINF_SUCCESS;
1110}
1111
1112
1113/**
1114 * Entry point.
1115 */
1116extern "C" DECLEXPORT(int) TrustedMain(int argc, char **argv, char **envp)
1117{
1118 int rc;
1119
1120 LogFlowFuncEnter();
1121
1122 NOREF(envp);
1123
1124#ifdef RT_OS_WINDOWS
1125 WSADATA wsaData;
1126 int err;
1127
1128 err = WSAStartup(MAKEWORD(2,2), &wsaData);
1129 if (err)
1130 {
1131 fprintf(stderr, "wsastartup: failed (%d)\n", err);
1132 return 1;
1133 }
1134#endif
1135
1136 SOCKET icmpsock4 = INVALID_SOCKET;
1137 SOCKET icmpsock6 = INVALID_SOCKET;
1138#ifndef RT_OS_DARWIN
1139 const int icmpstype = SOCK_RAW;
1140#else
1141 /* on OS X it's not privileged */
1142 const int icmpstype = SOCK_DGRAM;
1143#endif
1144
1145 icmpsock4 = socket(AF_INET, icmpstype, IPPROTO_ICMP);
1146 if (icmpsock4 == INVALID_SOCKET)
1147 {
1148 perror("IPPROTO_ICMP");
1149#ifdef VBOX_RAWSOCK_DEBUG_HELPER
1150 icmpsock4 = getrawsock(AF_INET);
1151#endif
1152 }
1153
1154 if (icmpsock4 != INVALID_SOCKET)
1155 {
1156#ifdef ICMP_FILTER // Linux specific
1157 struct icmp_filter flt = {
1158 ~(uint32_t)(
1159 (1U << ICMP_ECHOREPLY)
1160 | (1U << ICMP_DEST_UNREACH)
1161 | (1U << ICMP_TIME_EXCEEDED)
1162 )
1163 };
1164
1165 int status = setsockopt(icmpsock4, SOL_RAW, ICMP_FILTER,
1166 &flt, sizeof(flt));
1167 if (status < 0)
1168 {
1169 perror("ICMP_FILTER");
1170 }
1171#endif
1172 }
1173
1174 icmpsock6 = socket(AF_INET6, icmpstype, IPPROTO_ICMPV6);
1175 if (icmpsock6 == INVALID_SOCKET)
1176 {
1177 perror("IPPROTO_ICMPV6");
1178#ifdef VBOX_RAWSOCK_DEBUG_HELPER
1179 icmpsock6 = getrawsock(AF_INET6);
1180#endif
1181 }
1182
1183 if (icmpsock6 != INVALID_SOCKET)
1184 {
1185#ifdef ICMP6_FILTER // Windows doesn't support RFC 3542 API
1186 /*
1187 * XXX: We do this here for now, not in pxping.c, to avoid
1188 * name clashes between lwIP and system headers.
1189 */
1190 struct icmp6_filter flt;
1191 ICMP6_FILTER_SETBLOCKALL(&flt);
1192
1193 ICMP6_FILTER_SETPASS(ICMP6_ECHO_REPLY, &flt);
1194
1195 ICMP6_FILTER_SETPASS(ICMP6_DST_UNREACH, &flt);
1196 ICMP6_FILTER_SETPASS(ICMP6_PACKET_TOO_BIG, &flt);
1197 ICMP6_FILTER_SETPASS(ICMP6_TIME_EXCEEDED, &flt);
1198 ICMP6_FILTER_SETPASS(ICMP6_PARAM_PROB, &flt);
1199
1200 int status = setsockopt(icmpsock6, IPPROTO_ICMPV6, ICMP6_FILTER,
1201 &flt, sizeof(flt));
1202 if (status < 0)
1203 {
1204 perror("ICMP6_FILTER");
1205 }
1206#endif
1207 }
1208
1209 HRESULT hrc = com::Initialize();
1210 if (FAILED(hrc))
1211 {
1212#ifdef VBOX_WITH_XPCOM
1213 if (hrc == NS_ERROR_FILE_ACCESS_DENIED)
1214 {
1215 char szHome[RTPATH_MAX] = "";
1216 int vrc = com::GetVBoxUserHomeDirectory(szHome, sizeof(szHome), false);
1217 if (RT_SUCCESS(vrc))
1218 {
1219 closesocket(icmpsock4);
1220 closesocket(icmpsock6);
1221 return RTMsgErrorExit(RTEXITCODE_FAILURE,
1222 "Failed to initialize COM: %s: %Rhrf",
1223 szHome, hrc);
1224 }
1225 }
1226#endif // VBOX_WITH_XPCOM
1227 closesocket(icmpsock4);
1228 closesocket(icmpsock6);
1229 return RTMsgErrorExit(RTEXITCODE_FAILURE,
1230 "Failed to initialize COM: %Rhrf", hrc);
1231 }
1232
1233 rc = vboxNetNATLogInit(argc, argv);
1234 // shall we bail if we failed to init logging?
1235
1236 g_pLwipNat = new VBoxNetLwipNAT(icmpsock4, icmpsock6);
1237
1238 Log2(("NAT: initialization\n"));
1239 rc = g_pLwipNat->parseArgs(argc - 1, argv + 1);
1240 rc = (rc == 0) ? VINF_SUCCESS : VERR_GENERAL_FAILURE; /* XXX: FIXME */
1241
1242 if (RT_SUCCESS(rc))
1243 rc = g_pLwipNat->init();
1244
1245 if (RT_SUCCESS(rc))
1246 g_pLwipNat->run();
1247
1248 delete g_pLwipNat;
1249 return 0;
1250}
1251
1252
1253static int vboxNetNATLogInit(int argc, char **argv)
1254{
1255 size_t cch;
1256 int rc;
1257
1258 char szHome[RTPATH_MAX];
1259 rc = com::GetVBoxUserHomeDirectory(szHome, sizeof(szHome), false);
1260 if (RT_FAILURE(rc))
1261 return rc;
1262
1263 const char *pcszNetwork = NULL;
1264
1265 // XXX: This duplicates information from VBoxNetBaseService.cpp.
1266 // Perhaps option definitions should be exported as public static
1267 // member of VBoxNetBaseService?
1268 static const RTGETOPTDEF s_aOptions[] = {
1269 { "--network", 'n', RTGETOPT_REQ_STRING }
1270 };
1271
1272 RTGETOPTSTATE GetState;
1273 RTGetOptInit(&GetState, argc, argv, s_aOptions, RT_ELEMENTS(s_aOptions), 1,
1274 RTGETOPTINIT_FLAGS_NO_STD_OPTS);
1275
1276 RTGETOPTUNION ValueUnion;
1277 int ch;
1278 while ((ch = RTGetOpt(&GetState, &ValueUnion)))
1279 {
1280 if (ch == 'n')
1281 {
1282 pcszNetwork = ValueUnion.psz;
1283 break;
1284 }
1285 }
1286
1287 if (pcszNetwork == NULL)
1288 return VERR_MISSING;
1289
1290 char szNetwork[RTPATH_MAX];
1291 rc = RTStrCopy(szNetwork, sizeof(szNetwork), pcszNetwork);
1292 if (RT_FAILURE(rc))
1293 return rc;
1294
1295 // sanitize network name to be usable as a path component
1296 for (char *p = szNetwork; *p != '\0'; ++p)
1297 {
1298 if (RTPATH_IS_SEP(*p))
1299 *p = '_';
1300 }
1301
1302 char szLogFile[RTPATH_MAX];
1303 cch = RTStrPrintf(szLogFile, sizeof(szLogFile),
1304 "%s%c%s.log", szHome, RTPATH_DELIMITER, szNetwork);
1305 if (cch >= sizeof(szLogFile))
1306 {
1307 return VERR_BUFFER_OVERFLOW;
1308 }
1309
1310 // sanitize network name some more to be usable as environment variable
1311 for (char *p = szNetwork; *p != '\0'; ++p)
1312 {
1313 if (*p != '_'
1314 && (*p < '0' || '9' < *p)
1315 && (*p < 'a' || 'z' < *p)
1316 && (*p < 'A' || 'Z' < *p))
1317 {
1318 *p = '_';
1319 }
1320 }
1321
1322 char szEnvVarBase[128];
1323 cch = RTStrPrintf(szEnvVarBase, sizeof(szEnvVarBase),
1324 "VBOXNET_%s_RELEASE_LOG", szNetwork);
1325 if (cch >= sizeof(szEnvVarBase))
1326 return VERR_BUFFER_OVERFLOW;
1327
1328 rc = com::VBoxLogRelCreate("NAT Network",
1329 szLogFile,
1330 RTLOGFLAGS_PREFIX_TIME_PROG,
1331 "all all.restrict -default.restrict",
1332 szEnvVarBase,
1333 RTLOGDEST_FILE,
1334 32768 /* cMaxEntriesPerGroup */,
1335 0 /* cHistory */,
1336 0 /* uHistoryFileTime */,
1337 0 /* uHistoryFileSize */,
1338 NULL /*pErrInfo*/);
1339
1340 /*
1341 * Provide immediate feedback if corresponding LogRel level is
1342 * enabled. It's frustrating when you chase some rare event and
1343 * discover you didn't actually have the corresponding log level
1344 * enabled because of a typo in the environment variable name or
1345 * its content.
1346 */
1347#define LOG_PING(_log) _log((#_log " enabled\n"))
1348 LOG_PING(LogRel2);
1349 LOG_PING(LogRel3);
1350 LOG_PING(LogRel4);
1351 LOG_PING(LogRel5);
1352 LOG_PING(LogRel6);
1353 LOG_PING(LogRel7);
1354 LOG_PING(LogRel8);
1355 LOG_PING(LogRel9);
1356 LOG_PING(LogRel10);
1357 LOG_PING(LogRel11);
1358 LOG_PING(LogRel12);
1359
1360 return rc;
1361}
1362
1363
1364static int fetchNatPortForwardRules(const ComNatPtr& nat, bool fIsIPv6, VECNATSERVICEPF& vec)
1365{
1366 HRESULT hrc;
1367 com::SafeArray<BSTR> rules;
1368 if (fIsIPv6)
1369 hrc = nat->COMGETTER(PortForwardRules6)(ComSafeArrayAsOutParam(rules));
1370 else
1371 hrc = nat->COMGETTER(PortForwardRules4)(ComSafeArrayAsOutParam(rules));
1372 AssertComRCReturn(hrc, VERR_INTERNAL_ERROR);
1373
1374 NATSEVICEPORTFORWARDRULE Rule;
1375 for (size_t idxRules = 0; idxRules < rules.size(); ++idxRules)
1376 {
1377 Log(("%d-%s rule: %ls\n", idxRules, (fIsIPv6 ? "IPv6" : "IPv4"), rules[idxRules]));
1378 RT_ZERO(Rule);
1379
1380 int rc = netPfStrToPf(com::Utf8Str(rules[idxRules]).c_str(), fIsIPv6,
1381 &Rule.Pfr);
1382 if (RT_FAILURE(rc))
1383 continue;
1384
1385 vec.push_back(Rule);
1386 }
1387
1388 return VINF_SUCCESS;
1389}
1390
1391
1392#ifndef VBOX_WITH_HARDENING
1393
1394int main(int argc, char **argv, char **envp)
1395{
1396 int rc = RTR3InitExe(argc, &argv, RTR3INIT_FLAGS_SUPLIB);
1397 if (RT_FAILURE(rc))
1398 return RTMsgInitFailure(rc);
1399
1400 return TrustedMain(argc, argv, envp);
1401}
1402
1403# if defined(RT_OS_WINDOWS)
1404
1405# if 0 /* Some copy and paste from DHCP that nobody explained why was diabled. */
1406static LRESULT CALLBACK WindowProc(HWND hwnd,
1407 UINT uMsg,
1408 WPARAM wParam,
1409 LPARAM lParam
1410)
1411{
1412 if(uMsg == WM_DESTROY)
1413 {
1414 PostQuitMessage(0);
1415 return 0;
1416 }
1417 return DefWindowProc (hwnd, uMsg, wParam, lParam);
1418}
1419
1420static LPCWSTR g_WndClassName = L"VBoxNetNatLwipClass";
1421
1422static DWORD WINAPI MsgThreadProc(__in LPVOID lpParameter)
1423{
1424 HWND hwnd = 0;
1425 HINSTANCE hInstance = (HINSTANCE)GetModuleHandle (NULL);
1426 bool bExit = false;
1427
1428 /* Register the Window Class. */
1429 WNDCLASS wc;
1430 wc.style = 0;
1431 wc.lpfnWndProc = WindowProc;
1432 wc.cbClsExtra = 0;
1433 wc.cbWndExtra = sizeof(void *);
1434 wc.hInstance = hInstance;
1435 wc.hIcon = NULL;
1436 wc.hCursor = NULL;
1437 wc.hbrBackground = (HBRUSH)(COLOR_BACKGROUND + 1);
1438 wc.lpszMenuName = NULL;
1439 wc.lpszClassName = g_WndClassName;
1440
1441 ATOM atomWindowClass = RegisterClass(&wc);
1442
1443 if (atomWindowClass != 0)
1444 {
1445 /* Create the window. */
1446 hwnd = CreateWindowEx(WS_EX_TOOLWINDOW | WS_EX_TRANSPARENT | WS_EX_TOPMOST,
1447 g_WndClassName, g_WndClassName, WS_POPUPWINDOW,
1448 -200, -200, 100, 100, NULL, NULL, hInstance, NULL);
1449
1450 if (hwnd)
1451 {
1452 SetWindowPos(hwnd, HWND_TOPMOST, -200, -200, 0, 0,
1453 SWP_NOACTIVATE | SWP_HIDEWINDOW | SWP_NOCOPYBITS | SWP_NOREDRAW | SWP_NOSIZE);
1454
1455 MSG msg;
1456 while (GetMessage(&msg, NULL, 0, 0))
1457 {
1458 TranslateMessage(&msg);
1459 DispatchMessage(&msg);
1460 }
1461
1462 DestroyWindow (hwnd);
1463
1464 bExit = true;
1465 }
1466
1467 UnregisterClass (g_WndClassName, hInstance);
1468 }
1469
1470 if(bExit)
1471 {
1472 /* no need any accuracy here, in anyway the DHCP server usually gets terminated with TerminateProcess */
1473 exit(0);
1474 }
1475
1476 return 0;
1477}
1478# endif
1479
1480
1481/** (We don't want a console usually.) */
1482int WINAPI WinMain(HINSTANCE hInstance, HINSTANCE hPrevInstance, LPSTR lpCmdLine, int nCmdShow)
1483{
1484 RT_NOREF(hInstance, hPrevInstance, lpCmdLine, nCmdShow);
1485# if 0 /* some copy and paste from DHCP that nobody explained why was diabled. */
1486 NOREF(hInstance); NOREF(hPrevInstance); NOREF(lpCmdLine); NOREF(nCmdShow);
1487
1488 HANDLE hThread = CreateThread(
1489 NULL, /*__in_opt LPSECURITY_ATTRIBUTES lpThreadAttributes, */
1490 0, /*__in SIZE_T dwStackSize, */
1491 MsgThreadProc, /*__in LPTHREAD_START_ROUTINE lpStartAddress,*/
1492 NULL, /*__in_opt LPVOID lpParameter,*/
1493 0, /*__in DWORD dwCreationFlags,*/
1494 NULL /*__out_opt LPDWORD lpThreadId*/
1495 );
1496
1497 if(hThread != NULL)
1498 CloseHandle(hThread);
1499
1500# endif
1501 return main(__argc, __argv, environ);
1502}
1503# endif /* RT_OS_WINDOWS */
1504
1505#endif /* !VBOX_WITH_HARDENING */
Note: See TracBrowser for help on using the repository browser.

© 2025 Oracle Support Privacy / Do Not Sell My Info Terms of Use Trademark Policy Automated Access Etiquette