VirtualBox

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

Last change on this file since 58725 was 57416, checked in by vboxsync, 9 years ago

More DECLCALLBACK fixes; retired RTMemAutoPtr.

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