VirtualBox

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

Last change on this file since 54671 was 54671, checked in by vboxsync, 10 years ago

NAT networks: don't kill VBoxNetDHCP and VBoxNetNAT but send the INATNetworkStartStop event to ask them politely to shutdown

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