VirtualBox

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

Last change on this file since 50487 was 50487, checked in by vboxsync, 11 years ago

NATNet: clean up handling of port-forwarding rules a bit.
Don't assert what we don't control, deal with failure.
Use RTCMemAutoPtr to manage fwspec copy.
Add release logging to VBoxEventType_OnNATNetworkPortForward.

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