VirtualBox

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

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

Create ICMP sockets for ping proxy.

  • Property svn:eol-style set to native
  • Property svn:keywords set to Author Date Id Revision
File size: 41.9 KB
Line 
1/* $Id: VBoxNetLwipNAT.cpp 49689 2013-11-28 02:34:48Z 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/com.h>
21#include <VBox/com/listeners.h>
22#include <VBox/com/string.h>
23#include <VBox/com/Guid.h>
24#include <VBox/com/array.h>
25#include <VBox/com/ErrorInfo.h>
26#include <VBox/com/errorprint.h>
27#include <VBox/com/VirtualBox.h>
28#include <VBox/com/NativeEventQueue.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/utils.h>
52#define LOG_GROUP LOG_GROUP_NAT_SERVICE
53#include <VBox/log.h>
54
55#include <VBox/sup.h>
56#include <VBox/intnet.h>
57#include <VBox/intnetinline.h>
58#include <VBox/vmm/pdmnetinline.h>
59#include <VBox/vmm/vmm.h>
60#include <VBox/version.h>
61
62#ifndef RT_OS_WINDOWS
63# include <sys/poll.h>
64# include <sys/socket.h>
65# include <netinet/in.h>
66# ifdef RT_OS_LINUX
67# include <linux/icmp.h> /* ICMP_FILTER */
68# endif
69# include <netinet/icmp6.h>
70#endif
71
72#include <vector>
73#include <string>
74
75#include "../NetLib/VBoxNetLib.h"
76#include "../NetLib/VBoxNetBaseService.h"
77#include "VBoxLwipCore.h"
78
79extern "C"
80{
81/* bunch of LWIP headers */
82#include "lwip/opt.h"
83#ifdef LWIP_SOCKET
84# undef LWIP_SOCKET
85# define LWIP_SOCKET 0
86#endif
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#include "../NetLib/VBoxPortForwardString.h"
102
103static RTGETOPTDEF g_aGetOptDef[] =
104{
105 { "--port-forward4", 'p', RTGETOPT_REQ_STRING },
106 { "--port-forward6", 'P', RTGETOPT_REQ_STRING }
107};
108
109typedef struct NATSEVICEPORTFORWARDRULE
110{
111 PORTFORWARDRULE Pfr;
112 fwspec FWSpec;
113} NATSEVICEPORTFORWARDRULE, *PNATSEVICEPORTFORWARDRULE;
114
115typedef std::vector<NATSEVICEPORTFORWARDRULE> VECNATSERVICEPF;
116typedef VECNATSERVICEPF::iterator ITERATORNATSERVICEPF;
117typedef VECNATSERVICEPF::const_iterator CITERATORNATSERVICEPF;
118
119
120class VBoxNetLwipNAT;
121
122
123class NATNetworkListener
124{
125public:
126 NATNetworkListener():m_pNAT(NULL){}
127
128 HRESULT init(VBoxNetLwipNAT *pNAT)
129 {
130 AssertPtrReturn(pNAT, E_INVALIDARG);
131
132 m_pNAT = pNAT;
133 return S_OK;
134 }
135
136 HRESULT init()
137 {
138 m_pNAT = NULL;
139 return S_OK;
140 }
141
142 void uninit() { m_pNAT = NULL; }
143
144 STDMETHOD(HandleEvent)(VBoxEventType_T aEventType, IEvent *pEvent);
145
146private:
147 VBoxNetLwipNAT *m_pNAT;
148};
149typedef ListenerImpl<NATNetworkListener, VBoxNetLwipNAT *> NATNetworkListenerImpl;
150VBOX_LISTENER_DECLARE(NATNetworkListenerImpl)
151
152
153class VBoxNetLwipNAT: public VBoxNetBaseService
154{
155 friend class NATNetworkListener;
156 public:
157 VBoxNetLwipNAT(SOCKET icmpsock4, SOCKET icmpsock6);
158 virtual ~VBoxNetLwipNAT();
159 void usage(){ /* @todo: should be implemented */ };
160 int run();
161 virtual int init(void);
162 /* @todo: when configuration would be really needed */
163 virtual int parseOpt(int rc, const RTGETOPTUNION& getOptVal);
164 /* VBoxNetNAT always needs Main */
165 virtual bool isMainNeeded() const { return true; }
166 private:
167 struct proxy_options m_ProxyOptions;
168 struct sockaddr_in m_src4;
169 struct sockaddr_in6 m_src6;
170 /**
171 * place for registered local interfaces.
172 */
173 ip4_lomap m_lo2off[10];
174 ip4_lomap_desc m_loOptDescriptor;
175
176 uint16_t m_u16Mtu;
177 netif m_LwipNetIf;
178 /* Queues */
179 RTREQQUEUE hReqIntNet;
180 /* thread where we're waiting for a frames, no semaphores needed */
181 RTTHREAD hThrIntNetRecv;
182
183 /* Our NAT network descriptor in Main */
184 ComPtr<INATNetwork> m_net;
185 ComObjPtr<NATNetworkListenerImpl> m_listener;
186
187 ComPtr<IHost> m_host;
188 ComObjPtr<NATNetworkListenerImpl> m_vboxListener;
189
190 STDMETHOD(HandleEvent)(VBoxEventType_T aEventType, IEvent *pEvent);
191
192 const char **getHostNameservers();
193
194 RTSEMEVENT hSemSVC;
195 /* Only for debug needs, by default NAT service should load rules from SVC
196 * on startup, and then on sync them on events.
197 */
198 bool fDontLoadRulesOnStartup;
199 static void onLwipTcpIpInit(void *arg);
200 static void onLwipTcpIpFini(void *arg);
201 static err_t netifInit(netif *pNetif);
202 static err_t netifLinkoutput(netif *pNetif, pbuf *pBuf);
203 static int intNetThreadRecv(RTTHREAD, void *);
204 static void vboxNetLwipNATProcessXmit(void);
205
206 VECNATSERVICEPF m_vecPortForwardRule4;
207 VECNATSERVICEPF m_vecPortForwardRule6;
208
209 static int natServicePfRegister(NATSEVICEPORTFORWARDRULE& natServicePf);
210 static int natServiceProcessRegisteredPf(VECNATSERVICEPF& vecPf);
211};
212
213
214static VBoxNetLwipNAT *g_pLwipNat;
215
216STDMETHODIMP NATNetworkListener::HandleEvent(VBoxEventType_T aEventType, IEvent *pEvent)
217{
218 if (m_pNAT)
219 return m_pNAT->HandleEvent(aEventType, pEvent);
220 else
221 return E_FAIL;
222}
223
224
225
226STDMETHODIMP VBoxNetLwipNAT::HandleEvent(VBoxEventType_T aEventType,
227 IEvent *pEvent)
228{
229 HRESULT hrc = S_OK;
230 switch (aEventType)
231 {
232 case VBoxEventType_OnNATNetworkSetting:
233 {
234 ComPtr<INATNetworkSettingEvent> evSettings(pEvent);
235 // XXX: only handle IPv6 default route for now
236
237 if (!m_ProxyOptions.ipv6_enabled)
238 {
239 break;
240 }
241
242 BOOL fIPv6DefaultRoute = FALSE;
243 hrc = evSettings->COMGETTER(AdvertiseDefaultIPv6RouteEnabled)(&fIPv6DefaultRoute);
244 AssertReturn(SUCCEEDED(hrc), hrc);
245
246 if (m_ProxyOptions.ipv6_defroute == fIPv6DefaultRoute)
247 {
248 break;
249 }
250
251 m_ProxyOptions.ipv6_defroute = fIPv6DefaultRoute;
252 tcpip_callback_with_block(proxy_rtadvd_do_quick, &m_LwipNetIf, 0);
253
254 break;
255 }
256
257 case VBoxEventType_OnNATNetworkPortForward:
258 {
259 com::Bstr name, strHostAddr, strGuestAddr;
260 LONG lHostPort, lGuestPort;
261 BOOL fCreateFW, fIPv6FW;
262 NATProtocol_T proto = NATProtocol_TCP;
263
264
265 ComPtr<INATNetworkPortForwardEvent> pfEvt = pEvent;
266
267 hrc = pfEvt->COMGETTER(Name)(name.asOutParam());
268 AssertReturn(SUCCEEDED(hrc), hrc);
269
270 hrc = pfEvt->COMGETTER(Proto)(&proto);
271 AssertReturn(SUCCEEDED(hrc), hrc);
272
273 hrc = pfEvt->COMGETTER(HostIp)(strHostAddr.asOutParam());
274 AssertReturn(SUCCEEDED(hrc), hrc);
275
276 hrc = pfEvt->COMGETTER(HostPort)(&lHostPort);
277 AssertReturn(SUCCEEDED(hrc), hrc);
278
279 hrc = pfEvt->COMGETTER(GuestIp)(strGuestAddr.asOutParam());
280 AssertReturn(SUCCEEDED(hrc), hrc);
281
282 hrc = pfEvt->COMGETTER(GuestPort)(&lGuestPort);
283 AssertReturn(SUCCEEDED(hrc), hrc);
284
285 hrc = pfEvt->COMGETTER(Create)(&fCreateFW);
286 AssertReturn(SUCCEEDED(hrc), hrc);
287
288 hrc = pfEvt->COMGETTER(Ipv6)(&fIPv6FW);
289 AssertReturn(SUCCEEDED(hrc), hrc);
290
291 VECNATSERVICEPF& rules = (fIPv6FW ?
292 m_vecPortForwardRule6 :
293 m_vecPortForwardRule4);
294
295 NATSEVICEPORTFORWARDRULE r;
296
297 RT_ZERO(r);
298
299 if (name.length() > sizeof(r.Pfr.szPfrName))
300 {
301 hrc = E_INVALIDARG;
302 goto port_forward_done;
303 }
304
305 r.Pfr.fPfrIPv6 = fIPv6FW;
306
307 switch (proto)
308 {
309 case NATProtocol_TCP:
310 r.Pfr.iPfrProto = IPPROTO_TCP;
311 break;
312 case NATProtocol_UDP:
313 r.Pfr.iPfrProto = IPPROTO_UDP;
314 break;
315 default:
316 goto port_forward_done;
317 }
318
319
320 RTStrPrintf(r.Pfr.szPfrName, sizeof(r.Pfr.szPfrName),
321 "%s", com::Utf8Str(name).c_str());
322
323 RTStrPrintf(r.Pfr.szPfrHostAddr, sizeof(r.Pfr.szPfrHostAddr),
324 "%s", com::Utf8Str(strHostAddr).c_str());
325
326 /* XXX: limits should be checked */
327 r.Pfr.u16PfrHostPort = (uint16_t)lHostPort;
328
329 RTStrPrintf(r.Pfr.szPfrGuestAddr, sizeof(r.Pfr.szPfrGuestAddr),
330 "%s", com::Utf8Str(strGuestAddr).c_str());
331
332 /* XXX: limits should be checked */
333 r.Pfr.u16PfrGuestPort = (uint16_t)lGuestPort;
334
335 if (fCreateFW) /* Addition */
336 {
337 rules.push_back(r);
338
339 natServicePfRegister(rules.back());
340 }
341 else /* Deletion */
342 {
343 ITERATORNATSERVICEPF it;
344 for (it = rules.begin(); it != rules.end(); ++it)
345 {
346 /* compare */
347 NATSEVICEPORTFORWARDRULE& natFw = *it;
348 if ( natFw.Pfr.iPfrProto == r.Pfr.iPfrProto
349 && natFw.Pfr.u16PfrHostPort == r.Pfr.u16PfrHostPort
350 && (strncmp(natFw.Pfr.szPfrHostAddr, r.Pfr.szPfrHostAddr, INET6_ADDRSTRLEN) == 0)
351 && natFw.Pfr.u16PfrGuestPort == r.Pfr.u16PfrGuestPort
352 && (strncmp(natFw.Pfr.szPfrGuestAddr, r.Pfr.szPfrGuestAddr, INET6_ADDRSTRLEN) == 0))
353 {
354 fwspec *pFwCopy = (fwspec *)RTMemAllocZ(sizeof(fwspec));
355 if (!pFwCopy)
356 {
357 break;
358 }
359 memcpy(pFwCopy, &natFw.FWSpec, sizeof(fwspec));
360
361 /* We shouldn't care about pFwCopy this memory will be freed when
362 * will message will arrive to the destination.
363 */
364 portfwd_rule_del(pFwCopy);
365
366 rules.erase(it);
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 {
389 RTMemFree(ppcszNameServers);
390 }
391 break;
392 }
393 }
394 return hrc;
395}
396
397
398void VBoxNetLwipNAT::onLwipTcpIpInit(void* arg)
399{
400 AssertPtrReturnVoid(arg);
401 VBoxNetLwipNAT *pNat = static_cast<VBoxNetLwipNAT *>(arg);
402
403 HRESULT hrc = com::Initialize();
404 Assert(!FAILED(hrc));
405
406 proxy_arp_hook = pxremap_proxy_arp;
407 proxy_ip4_divert_hook = pxremap_ip4_divert;
408
409 proxy_na_hook = pxremap_proxy_na;
410 proxy_ip6_divert_hook = pxremap_ip6_divert;
411
412 /* lwip thread */
413 RTNETADDRIPV4 IpNetwork;
414 IpNetwork.u = g_pLwipNat->m_Ipv4Address.u & g_pLwipNat->m_Ipv4Netmask.u;
415
416 ip_addr LwipIpAddr, LwipIpNetMask, LwipIpNetwork;
417
418 memcpy(&LwipIpAddr, &g_pLwipNat->m_Ipv4Address, sizeof(ip_addr));
419 memcpy(&LwipIpNetMask, &g_pLwipNat->m_Ipv4Netmask, sizeof(ip_addr));
420 memcpy(&LwipIpNetwork, &IpNetwork, sizeof(ip_addr));
421
422 netif *pNetif = netif_add(&g_pLwipNat->m_LwipNetIf /* Lwip Interface */,
423 &LwipIpAddr /* IP address*/,
424 &LwipIpNetMask /* Network mask */,
425 &LwipIpAddr /* gateway address, @todo: is self IP acceptable? */,
426 g_pLwipNat /* state */,
427 VBoxNetLwipNAT::netifInit /* netif_init_fn */,
428 lwip_tcpip_input /* netif_input_fn */);
429
430 AssertPtrReturnVoid(pNetif);
431
432 netif_set_up(pNetif);
433 netif_set_link_up(pNetif);
434
435 if (pNat->m_ProxyOptions.ipv6_enabled) {
436 /*
437 * XXX: lwIP currently only ever calls mld6_joingroup() in
438 * nd6_tmr() for fresh tentative addresses, which is a wrong place
439 * to do it - but I'm not keen on fixing this properly for now
440 * (with correct handling of interface up and down transitions,
441 * etc). So stick it here as a kludge.
442 */
443 for (int i = 0; i <= 1; ++i) {
444 ip6_addr_t *paddr = netif_ip6_addr(pNetif, i);
445
446 ip6_addr_t solicited_node_multicast_address;
447 ip6_addr_set_solicitednode(&solicited_node_multicast_address,
448 paddr->addr[3]);
449 mld6_joingroup(paddr, &solicited_node_multicast_address);
450 }
451
452 /*
453 * XXX: We must join the solicited-node multicast for the
454 * addresses we do IPv6 NA-proxy for. We map IPv6 loopback to
455 * proxy address + 1. We only need the low 24 bits, and those are
456 * fixed.
457 */
458 {
459 ip6_addr_t solicited_node_multicast_address;
460
461 ip6_addr_set_solicitednode(&solicited_node_multicast_address,
462 /* last 24 bits of the address */
463 PP_HTONL(0x00000002));
464 mld6_netif_joingroup(pNetif, &solicited_node_multicast_address);
465 }
466 }
467
468 proxy_init(&g_pLwipNat->m_LwipNetIf, &g_pLwipNat->m_ProxyOptions);
469
470 natServiceProcessRegisteredPf(g_pLwipNat->m_vecPortForwardRule4);
471 natServiceProcessRegisteredPf(g_pLwipNat->m_vecPortForwardRule6);
472}
473
474
475void VBoxNetLwipNAT::onLwipTcpIpFini(void* arg)
476{
477 AssertPtrReturnVoid(arg);
478 VBoxNetLwipNAT *pThis = (VBoxNetLwipNAT *)arg;
479
480 /* XXX: proxy finalization */
481 netif_set_link_down(&g_pLwipNat->m_LwipNetIf);
482 netif_set_down(&g_pLwipNat->m_LwipNetIf);
483 netif_remove(&g_pLwipNat->m_LwipNetIf);
484
485}
486
487/*
488 * Callback for netif_add() to initialize the interface.
489 */
490err_t VBoxNetLwipNAT::netifInit(netif *pNetif)
491{
492 err_t rcLwip = ERR_OK;
493
494 AssertPtrReturn(pNetif, ERR_ARG);
495
496 VBoxNetLwipNAT *pNat = static_cast<VBoxNetLwipNAT *>(pNetif->state);
497 AssertPtrReturn(pNat, ERR_ARG);
498
499 LogFlowFunc(("ENTER: pNetif[%c%c%d]\n", pNetif->name[0], pNetif->name[1], pNetif->num));
500 /* validity */
501 AssertReturn( pNetif->name[0] == 'N'
502 && pNetif->name[1] == 'T', ERR_ARG);
503
504
505 pNetif->hwaddr_len = sizeof(RTMAC);
506 memcpy(pNetif->hwaddr, &pNat->m_MacAddress, sizeof(RTMAC));
507
508 pNat->m_u16Mtu = 1500; // XXX: FIXME
509 pNetif->mtu = pNat->m_u16Mtu;
510
511 pNetif->flags = NETIF_FLAG_BROADCAST
512 | NETIF_FLAG_ETHARP /* Don't bother driver with ARP and let Lwip resolve ARP handling */
513 | NETIF_FLAG_ETHERNET; /* Lwip works with ethernet too */
514
515 pNetif->linkoutput = netifLinkoutput; /* ether-level-pipe */
516 pNetif->output = lwip_etharp_output; /* ip-pipe */
517
518 if (pNat->m_ProxyOptions.ipv6_enabled) {
519 pNetif->output_ip6 = ethip6_output;
520
521 /* IPv6 link-local address in slot 0 */
522 netif_create_ip6_linklocal_address(pNetif, /* :from_mac_48bit */ 1);
523 netif_ip6_addr_set_state(pNetif, 0, IP6_ADDR_PREFERRED); // skip DAD
524
525 /*
526 * RFC 4193 Locally Assigned Global ID (ULA) in slot 1
527 * [fd17:625c:f037:XXXX::1] where XXXX, 16 bit Subnet ID, are two
528 * bytes from the middle of the IPv4 address, e.g. :dead: for
529 * 10.222.173.1
530 */
531 u8_t nethi = ip4_addr2(&pNetif->ip_addr);
532 u8_t netlo = ip4_addr3(&pNetif->ip_addr);
533
534 ip6_addr_t *paddr = netif_ip6_addr(pNetif, 1);
535 IP6_ADDR(paddr, 0, 0xFD, 0x17, 0x62, 0x5C);
536 IP6_ADDR(paddr, 1, 0xF0, 0x37, nethi, netlo);
537 IP6_ADDR(paddr, 2, 0x00, 0x00, 0x00, 0x00);
538 IP6_ADDR(paddr, 3, 0x00, 0x00, 0x00, 0x01);
539 netif_ip6_addr_set_state(pNetif, 1, IP6_ADDR_PREFERRED);
540
541#if LWIP_IPV6_SEND_ROUTER_SOLICIT
542 pNetif->rs_count = 0;
543#endif
544 }
545
546 LogFlowFunc(("LEAVE: %d\n", rcLwip));
547 return rcLwip;
548}
549
550
551/**
552 * Intnet-recv thread
553 */
554int VBoxNetLwipNAT::intNetThreadRecv(RTTHREAD, void *)
555{
556 int rc = VINF_SUCCESS;
557
558 /* 1. initialization and connection */
559 HRESULT hrc = com::Initialize();
560 if (FAILED(hrc))
561 return RTMsgErrorExit(RTEXITCODE_FAILURE, "Failed to initialize COM!");
562
563 /* Well we're ready */
564 PINTNETRINGBUF pRingBuf = &g_pLwipNat->m_pIfBuf->Recv;
565
566 for (;;)
567 {
568 /*
569 * Wait for a packet to become available.
570 */
571 /* 2. waiting for request for */
572 rc = g_pLwipNat->waitForIntNetEvent(2000);
573 if (RT_FAILURE(rc))
574 {
575 if (rc == VERR_TIMEOUT || rc == VERR_INTERRUPTED)
576 {
577 /* do we want interrupt anyone ??? */
578 continue;
579 }
580 LogRel(("VBoxNetNAT: waitForIntNetEvent returned %Rrc\n", rc));
581 AssertRCReturn(rc,ERR_IF);
582 }
583
584 /*
585 * Process the receive buffer.
586 */
587 PCINTNETHDR pHdr;
588
589 while ((pHdr = IntNetRingGetNextFrameToRead(pRingBuf)) != NULL)
590 {
591 uint8_t const u8Type = pHdr->u8Type;
592 size_t cbFrame = pHdr->cbFrame;
593 uint8_t *pu8Frame = NULL;
594 pbuf *pPbufHdr = NULL;
595 pbuf *pPbuf = NULL;
596 switch (u8Type)
597 {
598
599 case INTNETHDR_TYPE_FRAME:
600 /* @todo:should it be really here?
601 * Well well well, we're accessing lwip code here
602 */
603 pPbufHdr = pPbuf = pbuf_alloc(PBUF_RAW, pHdr->cbFrame, PBUF_POOL);
604 if (!pPbuf)
605 {
606 LogRel(("NAT: Can't allocate send buffer cbFrame=%u\n", cbFrame));
607 break;
608 }
609 Assert(pPbufHdr->tot_len == cbFrame);
610 pu8Frame = (uint8_t *)IntNetHdrGetFramePtr(pHdr, g_pLwipNat->m_pIfBuf);
611 while(pPbuf)
612 {
613 memcpy(pPbuf->payload, pu8Frame, pPbuf->len);
614 pu8Frame += pPbuf->len;
615 pPbuf = pPbuf->next;
616 }
617
618 g_pLwipNat->m_LwipNetIf.input(pPbufHdr, &g_pLwipNat->m_LwipNetIf);
619
620 AssertReleaseRC(rc);
621 break;
622 case INTNETHDR_TYPE_GSO:
623 {
624 PCPDMNETWORKGSO pGso = IntNetHdrGetGsoContext(pHdr,
625 g_pLwipNat->m_pIfBuf);
626 if (!PDMNetGsoIsValid(pGso, cbFrame,
627 cbFrame - sizeof(PDMNETWORKGSO)))
628 break;
629 cbFrame -= sizeof(PDMNETWORKGSO);
630 uint8_t abHdrScratch[256];
631 uint32_t const cSegs = PDMNetGsoCalcSegmentCount(pGso,
632 cbFrame);
633 for (size_t iSeg = 0; iSeg < cSegs; iSeg++)
634 {
635 uint32_t cbSegFrame;
636 void *pvSegFrame =
637 PDMNetGsoCarveSegmentQD(pGso,
638 (uint8_t *)(pGso + 1),
639 cbFrame,
640 abHdrScratch,
641 iSeg,
642 cSegs,
643 &cbSegFrame);
644
645 pPbuf = pbuf_alloc(PBUF_RAW, cbSegFrame, PBUF_POOL);
646 if (!pPbuf)
647 {
648 LogRel(("NAT: Can't allocate send buffer cbFrame=%u\n", cbSegFrame));
649 break;
650 }
651 Assert( !pPbuf->next
652 && pPbuf->len == cbSegFrame);
653 memcpy(pPbuf->payload, pvSegFrame, cbSegFrame);
654 g_pLwipNat->m_LwipNetIf.input(pPbuf, &g_pLwipNat->m_LwipNetIf);
655
656 }
657
658 }
659 break;
660 case INTNETHDR_TYPE_PADDING:
661 break;
662 default:
663 STAM_REL_COUNTER_INC(&g_pLwipNat->m_pIfBuf->cStatBadFrames);
664 break;
665 }
666 IntNetRingSkipFrame(&g_pLwipNat->m_pIfBuf->Recv);
667
668 } /* loop */
669 }
670 /* 3. deinitilization and termination */
671 LogFlowFuncLeaveRC(rc);
672 return rc;
673}
674
675
676/**
677 *
678 */
679void VBoxNetLwipNAT::vboxNetLwipNATProcessXmit()
680{
681 int rc = VINF_SUCCESS;
682 INTNETIFSENDREQ SendReq;
683 SendReq.Hdr.u32Magic = SUPVMMR0REQHDR_MAGIC;
684 SendReq.Hdr.cbReq = sizeof(SendReq);
685 SendReq.pSession = g_pLwipNat->m_pSession;
686 SendReq.hIf = g_pLwipNat->m_hIf;
687 rc = SUPR3CallVMMR0Ex(NIL_RTR0PTR, NIL_VMCPUID, VMMR0_DO_INTNET_IF_SEND, 0, &SendReq.Hdr);
688 AssertRC(rc);
689}
690
691
692err_t VBoxNetLwipNAT::netifLinkoutput(netif *pNetif, pbuf *pPBuf)
693{
694 int rc = VINF_SUCCESS;
695 err_t rcLwip = ERR_OK;
696 AssertPtrReturn(pNetif, ERR_ARG);
697 AssertPtrReturn(pPBuf, ERR_ARG);
698 AssertReturn((void *)g_pLwipNat == pNetif->state, ERR_ARG);
699 LogFlowFunc(("ENTER: pNetif[%c%c%d], pPbuf:%p\n",
700 pNetif->name[0],
701 pNetif->name[1],
702 pNetif->num,
703 pPBuf));
704
705 /*
706 * We're on the lwip thread ...
707 * try accure Xmit lock (actually we DO accure the lock ... )
708 * 1. we've entered csXmit so we should create frame
709 * 1.a. Frame creation success see 2.
710 * 1.b. (hm ... what about queue processing in place)
711 * 1.c. 2nd attempt create frame
712 * 1.d. Unlock the Xmit
713 * 1.e. goto BUSY.1
714 * 2. Copy pbuf to the frame
715 * 3. Send
716 * 4. leave csXmit & return.
717 *
718 * @todo: perhaps we can use it for optimization,
719 * e.g. drop UDP and reoccure lock on TCP NOTE: now BUSY is unachievable!
720 * Otherwise (BUSY)
721 * 1. Unbuffered (drop)
722 * (buffered)
723 * 1. Copy pbuf to entermediate buffer.
724 * 2. Add call buffer to the queue
725 * 3. return.
726 */
727 /* see p.1 */
728 rc = VINF_SUCCESS;
729 PINTNETHDR pHdr = NULL;
730 uint8_t *pu8Frame = NULL;
731 int offFrame = 0;
732 int idxSg = 0;
733 struct pbuf *pPBufPtr = pPBuf;
734 /* Allocate frame, and pad it if required. */
735 rc = IntNetRingAllocateFrame(&g_pLwipNat->m_pIfBuf->Send, pPBuf->tot_len, &pHdr, (void **)&pu8Frame);
736 if (RT_SUCCESS(rc))
737 {
738 /* see p. 2 */
739 while (pPBufPtr)
740 {
741 memcpy(&pu8Frame[offFrame], pPBufPtr->payload, pPBufPtr->len);
742 offFrame += pPBufPtr->len;
743 pPBufPtr = pPBufPtr->next;
744 }
745 }
746 if (RT_FAILURE(rc))
747 {
748 /* Could it be that some frames are still in the ring buffer */
749 /* 1.c */
750 AssertMsgFailed(("Debug Me!"));
751 }
752
753 /* Commit - what really this function do */
754 IntNetRingCommitFrameEx(&g_pLwipNat->m_pIfBuf->Send, pHdr, pPBuf->tot_len);
755
756 g_pLwipNat->vboxNetLwipNATProcessXmit();
757
758 AssertRCReturn(rc, ERR_IF);
759 LogFlowFunc(("LEAVE: %d\n", rcLwip));
760 return rcLwip;
761}
762
763
764VBoxNetLwipNAT::VBoxNetLwipNAT(SOCKET icmpsock4, SOCKET icmpsock6)
765{
766 LogFlowFuncEnter();
767
768 m_ProxyOptions.ipv6_enabled = 0;
769 m_ProxyOptions.ipv6_defroute = 0;
770 m_ProxyOptions.icmpsock4 = icmpsock4;
771 m_ProxyOptions.icmpsock6 = icmpsock6;
772 m_ProxyOptions.tftp_root = NULL;
773 m_ProxyOptions.src4 = NULL;
774 m_ProxyOptions.src6 = NULL;
775 memset(&m_src4, 0, sizeof(m_src4));
776 memset(&m_src6, 0, sizeof(m_src6));
777 m_src4.sin_family = AF_INET;
778 m_src6.sin6_family = AF_INET6;
779#if HAVE_SA_LEN
780 m_src4.sin_len = sizeof(m_src4);
781 m_src6.sin6_len = sizeof(m_src6);
782#endif
783 m_ProxyOptions.nameservers = NULL;
784
785 m_LwipNetIf.name[0] = 'N';
786 m_LwipNetIf.name[1] = 'T';
787 m_MacAddress.au8[0] = 0x52;
788 m_MacAddress.au8[1] = 0x54;
789 m_MacAddress.au8[2] = 0;
790 m_MacAddress.au8[3] = 0x12;
791 m_MacAddress.au8[4] = 0x35;
792 m_MacAddress.au8[5] = 0;
793 m_Ipv4Address.u = RT_MAKE_U32_FROM_U8( 10, 0, 2, 2); // NB: big-endian
794 m_Ipv4Netmask.u = RT_H2N_U32_C(0xffffff00);
795
796 fDontLoadRulesOnStartup = false;
797
798 for(unsigned int i = 0; i < RT_ELEMENTS(g_aGetOptDef); ++i)
799 m_vecOptionDefs.push_back(&g_aGetOptDef[i]);
800
801 m_enmTrunkType = kIntNetTrunkType_SrvNat;
802
803 LogFlowFuncLeave();
804}
805
806
807VBoxNetLwipNAT::~VBoxNetLwipNAT()
808{
809 if (m_ProxyOptions.tftp_root != NULL)
810 {
811 RTStrFree((char *)m_ProxyOptions.tftp_root);
812 }
813}
814
815
816int VBoxNetLwipNAT::natServicePfRegister(NATSEVICEPORTFORWARDRULE& natPf)
817{
818 int lrc = 0;
819 int rc = VINF_SUCCESS;
820 int socketSpec = SOCK_STREAM;
821 char *pszHostAddr;
822 int sockFamily = (natPf.Pfr.fPfrIPv6 ? PF_INET6 : PF_INET);
823
824 switch(natPf.Pfr.iPfrProto)
825 {
826 case IPPROTO_TCP:
827 socketSpec = SOCK_STREAM;
828 break;
829 case IPPROTO_UDP:
830 socketSpec = SOCK_DGRAM;
831 break;
832 default:
833 return VERR_IGNORED; /* Ah, just ignore the garbage */
834 }
835
836 pszHostAddr = natPf.Pfr.szPfrHostAddr;
837
838 /* XXX: workaround for inet_pton and an empty ipv4 address
839 * in rule declaration.
840 */
841 if ( sockFamily == PF_INET
842 && pszHostAddr[0] == 0)
843 pszHostAddr = (char *)"0.0.0.0"; /* XXX: fix it! without type cast */
844
845
846 lrc = fwspec_set(&natPf.FWSpec,
847 sockFamily,
848 socketSpec,
849 pszHostAddr,
850 natPf.Pfr.u16PfrHostPort,
851 natPf.Pfr.szPfrGuestAddr,
852 natPf.Pfr.u16PfrGuestPort);
853
854 AssertReturn(!lrc, VERR_IGNORED);
855
856 fwspec *pFwCopy = (fwspec *)RTMemAllocZ(sizeof(fwspec));
857 AssertPtrReturn(pFwCopy, VERR_IGNORED);
858
859 /*
860 * We need pass the copy, because we can't be sure
861 * how much this pointer will be valid in LWIP environment.
862 */
863 memcpy(pFwCopy, &natPf.FWSpec, sizeof(fwspec));
864
865 lrc = portfwd_rule_add(pFwCopy);
866
867 AssertReturn(!lrc, VERR_IGNORED);
868
869 return VINF_SUCCESS;
870}
871
872
873int VBoxNetLwipNAT::natServiceProcessRegisteredPf(VECNATSERVICEPF& vecRules){
874 ITERATORNATSERVICEPF it;
875 for (it = vecRules.begin();
876 it != vecRules.end(); ++it)
877 {
878 int rc = natServicePfRegister((*it));
879 if (RT_FAILURE(rc))
880 {
881 LogRel(("PF: %s is ignored\n", (*it).Pfr.szPfrName));
882 continue;
883 }
884 }
885 return VINF_SUCCESS;
886}
887
888
889int VBoxNetLwipNAT::init()
890{
891 HRESULT hrc;
892 LogFlowFuncEnter();
893
894
895 /* virtualbox initialized in super class */
896
897 int rc = ::VBoxNetBaseService::init();
898 AssertRCReturn(rc, rc);
899
900 hrc = virtualbox->FindNATNetworkByName(com::Bstr(m_Network.c_str()).raw(),
901 m_net.asOutParam());
902 AssertComRCReturn(hrc, VERR_NOT_FOUND);
903
904 hrc = m_listener.createObject();
905 AssertComRCReturn(hrc, VERR_INTERNAL_ERROR);
906
907 hrc = m_listener->init(new NATNetworkListener(), this);
908 AssertComRCReturn(hrc, VERR_INTERNAL_ERROR);
909
910 ComPtr<IEventSource> esNet;
911 hrc = m_net->COMGETTER(EventSource)(esNet.asOutParam());
912 AssertComRC(hrc);
913
914 com::SafeArray<VBoxEventType_T> aNetEvents;
915 aNetEvents.push_back(VBoxEventType_OnNATNetworkPortForward);
916 aNetEvents.push_back(VBoxEventType_OnNATNetworkSetting);
917 hrc = esNet->RegisterListener(m_listener, ComSafeArrayAsInParam(aNetEvents), true);
918 AssertComRCReturn(hrc, VERR_INTERNAL_ERROR);
919
920
921 // resolver changes are reported on vbox but are retrieved from
922 // host so stash a pointer for future lookups
923 hrc = virtualbox->COMGETTER(Host)(m_host.asOutParam());
924 AssertComRCReturn(hrc, VERR_INTERNAL_ERROR);
925
926 hrc = m_vboxListener.createObject();
927 AssertComRCReturn(hrc, VERR_INTERNAL_ERROR);
928
929 hrc = m_vboxListener->init(new NATNetworkListener(), this);
930 AssertComRCReturn(hrc, VERR_INTERNAL_ERROR);
931
932 ComPtr<IEventSource> esVBox;
933 hrc = virtualbox->COMGETTER(EventSource)(esVBox.asOutParam());
934 AssertComRC(hrc);
935
936 com::SafeArray<VBoxEventType_T> aVBoxEvents;
937 aVBoxEvents.push_back(VBoxEventType_OnHostNameResolutionConfigurationChange);
938 hrc = esVBox->RegisterListener(m_vboxListener, ComSafeArrayAsInParam(aVBoxEvents), true);
939 AssertComRCReturn(hrc, VERR_INTERNAL_ERROR);
940
941
942 BOOL fIPv6Enabled = FALSE;
943 hrc = m_net->COMGETTER(IPv6Enabled)(&fIPv6Enabled);
944 AssertComRCReturn(hrc, VERR_NOT_FOUND);
945
946 BOOL fIPv6DefaultRoute = FALSE;
947 if (fIPv6Enabled)
948 {
949 hrc = m_net->COMGETTER(AdvertiseDefaultIPv6RouteEnabled)(&fIPv6DefaultRoute);
950 AssertComRCReturn(hrc, VERR_NOT_FOUND);
951 }
952
953 m_ProxyOptions.ipv6_enabled = fIPv6Enabled;
954 m_ProxyOptions.ipv6_defroute = fIPv6DefaultRoute;
955
956
957 com::Bstr bstrSourceIp4Key = com::BstrFmt("NAT/%s/SourceIp4",m_Network.c_str());
958 com::Bstr bstrSourceIpX;
959 hrc = virtualbox->GetExtraData(bstrSourceIp4Key.raw(), bstrSourceIpX.asOutParam());
960 if (SUCCEEDED(hrc))
961 {
962 RTNETADDRIPV4 addr;
963 rc = RTNetStrToIPv4Addr(com::Utf8Str(bstrSourceIpX).c_str(), &addr);
964 if (RT_SUCCESS(rc))
965 {
966 RT_ZERO(m_src4);
967
968 m_src4.sin_addr.s_addr = addr.u;
969 m_ProxyOptions.src4 = &m_src4;
970
971 bstrSourceIpX.setNull();
972 }
973 }
974
975 if (!fDontLoadRulesOnStartup)
976 {
977 /* XXX: extract function and do not duplicate */
978 com::SafeArray<BSTR> rules;
979 hrc = m_net->COMGETTER(PortForwardRules4)(ComSafeArrayAsOutParam(rules));
980 Assert(SUCCEEDED(hrc));
981
982 size_t idxRules = 0;
983 for (idxRules = 0; idxRules < rules.size(); ++idxRules)
984 {
985 Log(("%d-rule: %ls\n", idxRules, rules[idxRules]));
986 NATSEVICEPORTFORWARDRULE Rule;
987 RT_ZERO(Rule);
988 rc = netPfStrToPf(com::Utf8Str(rules[idxRules]).c_str(), 0, &Rule.Pfr);
989 AssertRC(rc);
990 m_vecPortForwardRule4.push_back(Rule);
991 }
992
993 rules.setNull();
994 hrc = m_net->COMGETTER(PortForwardRules6)(ComSafeArrayAsOutParam(rules));
995 Assert(SUCCEEDED(hrc));
996
997 for (idxRules = 0; idxRules < rules.size(); ++idxRules)
998 {
999 Log(("%d-rule: %ls\n", idxRules, rules[idxRules]));
1000 NATSEVICEPORTFORWARDRULE Rule;
1001 netPfStrToPf(com::Utf8Str(rules[idxRules]).c_str(), 1, &Rule.Pfr);
1002 m_vecPortForwardRule6.push_back(Rule);
1003 }
1004 } /* if (!fDontLoadRulesOnStartup) */
1005
1006 com::SafeArray<BSTR> strs;
1007 int count_strs;
1008 hrc = m_net->COMGETTER(LocalMappings)(ComSafeArrayAsOutParam(strs));
1009 if ( SUCCEEDED(hrc)
1010 && (count_strs = strs.size()))
1011 {
1012 unsigned int j = 0;
1013 int i;
1014
1015 for (i = 0; i < count_strs && j < RT_ELEMENTS(m_lo2off); ++i)
1016 {
1017 char szAddr[17];
1018 RTNETADDRIPV4 ip4addr;
1019 char *pszTerm;
1020 uint32_t u32Off;
1021 com::Utf8Str strLo2Off(strs[i]);
1022 const char *pszLo2Off = strLo2Off.c_str();
1023
1024 RT_ZERO(szAddr);
1025
1026 pszTerm = RTStrStr(pszLo2Off, "=");
1027
1028 if ( !pszTerm
1029 || (pszTerm - pszLo2Off) >= 17)
1030 continue;
1031
1032 memcpy(szAddr, pszLo2Off, (pszTerm - pszLo2Off));
1033 rc = RTNetStrToIPv4Addr(szAddr, &ip4addr);
1034 if (RT_FAILURE(rc))
1035 continue;
1036
1037 u32Off = RTStrToUInt32(pszTerm + 1);
1038 if (u32Off == 0)
1039 continue;
1040
1041 ip4_addr_set_u32(&m_lo2off[j].loaddr, ip4addr.u);
1042 m_lo2off[j].off = u32Off;
1043 ++j;
1044 }
1045
1046 m_loOptDescriptor.lomap = m_lo2off;
1047 m_loOptDescriptor.num_lomap = j;
1048 m_ProxyOptions.lomap_desc = &m_loOptDescriptor;
1049 }
1050
1051 com::Bstr bstr;
1052 hrc = virtualbox->COMGETTER(HomeFolder)(bstr.asOutParam());
1053 AssertComRCReturn(hrc, VERR_NOT_FOUND);
1054 if (!bstr.isEmpty())
1055 {
1056 com::Utf8Str strTftpRoot(com::Utf8StrFmt("%ls%c%s",
1057 bstr.raw(), RTPATH_DELIMITER, "TFTP"));
1058 char *pszStrTemp; // avoid const char ** vs char **
1059 rc = RTStrUtf8ToCurrentCP(&pszStrTemp, strTftpRoot.c_str());
1060 AssertRC(rc);
1061 m_ProxyOptions.tftp_root = pszStrTemp;
1062 }
1063
1064 m_ProxyOptions.nameservers = getHostNameservers();
1065
1066 /* end of COM initialization */
1067
1068 rc = RTSemEventCreate(&hSemSVC);
1069 AssertRCReturn(rc, rc);
1070
1071 rc = RTReqQueueCreate(&hReqIntNet);
1072 AssertRCReturn(rc, rc);
1073
1074 rc = g_pLwipNat->tryGoOnline();
1075 if (RT_FAILURE(rc))
1076 {
1077 return rc;
1078 }
1079
1080 vboxLwipCoreInitialize(VBoxNetLwipNAT::onLwipTcpIpInit, this);
1081
1082 rc = RTThreadCreate(&g_pLwipNat->hThrIntNetRecv, /* thread handle*/
1083 VBoxNetLwipNAT::intNetThreadRecv, /* routine */
1084 NULL, /* user data */
1085 128 * _1K, /* stack size */
1086 RTTHREADTYPE_IO, /* type */
1087 0, /* flags, @todo: waitable ?*/
1088 "INTNET-RECV");
1089 AssertRCReturn(rc,rc);
1090
1091
1092
1093 LogFlowFuncLeaveRC(rc);
1094 return rc;
1095}
1096
1097
1098const char **VBoxNetLwipNAT::getHostNameservers()
1099{
1100 HRESULT hrc;
1101
1102 if (m_host.isNull())
1103 {
1104 return NULL;
1105 }
1106
1107 com::SafeArray<BSTR> aNameServers;
1108 hrc = m_host->COMGETTER(NameServers)(ComSafeArrayAsOutParam(aNameServers));
1109 if (FAILED(hrc))
1110 {
1111 return NULL;
1112 }
1113
1114 const size_t cNameServers = aNameServers.size();
1115 if (cNameServers == 0)
1116 {
1117 return NULL;
1118 }
1119
1120 const char **ppcszNameServers =
1121 (const char **)RTMemAllocZ(sizeof(char *) * (cNameServers + 1));
1122 if (ppcszNameServers == NULL)
1123 {
1124 return NULL;
1125 }
1126
1127 size_t idxLast = 0;
1128 for (size_t i = 0; i < cNameServers; ++i)
1129 {
1130 com::Utf8Str strNameServer(aNameServers[i]);
1131 ppcszNameServers[idxLast] = RTStrDup(strNameServer.c_str());
1132 if (ppcszNameServers[idxLast] != NULL)
1133 {
1134 ++idxLast;
1135 }
1136 }
1137
1138 if (idxLast == 0)
1139 {
1140 RTMemFree(ppcszNameServers);
1141 return NULL;
1142 }
1143
1144 return ppcszNameServers;
1145}
1146
1147
1148int VBoxNetLwipNAT::parseOpt(int rc, const RTGETOPTUNION& Val)
1149{
1150 switch (rc)
1151 {
1152 case 'p':
1153 case 'P':
1154 {
1155 NATSEVICEPORTFORWARDRULE Rule;
1156 VECNATSERVICEPF& rules = (rc == 'P'?
1157 m_vecPortForwardRule6
1158 : m_vecPortForwardRule4);
1159
1160 fDontLoadRulesOnStartup = true;
1161
1162 RT_ZERO(Rule);
1163
1164 int irc = netPfStrToPf(Val.psz, (rc == 'P'), &Rule.Pfr);
1165 rules.push_back(Rule);
1166 return VINF_SUCCESS;
1167 }
1168 default:;
1169 }
1170 return VERR_NOT_FOUND;
1171}
1172
1173
1174int VBoxNetLwipNAT::run()
1175{
1176 /* EventQueue processing from VBoxHeadless.cpp */
1177 com::NativeEventQueue *gEventQ = NULL;
1178 gEventQ = com::NativeEventQueue::getMainEventQueue();
1179 while(true)
1180 {
1181 /* XXX:todo: graceful termination */
1182 gEventQ->processEventQueue(0);
1183 gEventQ->processEventQueue(500);
1184 }
1185
1186 vboxLwipCoreFinalize(VBoxNetLwipNAT::onLwipTcpIpFini, this);
1187
1188 m_vecPortForwardRule4.clear();
1189 m_vecPortForwardRule6.clear();
1190
1191 return VINF_SUCCESS;
1192}
1193
1194
1195/**
1196 * Entry point.
1197 */
1198extern "C" DECLEXPORT(int) TrustedMain(int argc, char **argv, char **envp)
1199{
1200 LogFlowFuncEnter();
1201
1202 NOREF(envp);
1203
1204#ifdef RT_OS_WINDOWS
1205 WSADATA wsaData;
1206 int err;
1207
1208 err = WSAStartup(MAKEWORD(2,2), &wsaData);
1209 if (err)
1210 {
1211 fprintf(stderr, "wsastartup: failed (%d)\n", err);
1212 return 1;
1213 }
1214#endif
1215
1216 SOCKET icmpsock4 = INVALID_SOCKET;
1217 SOCKET icmpsock6 = INVALID_SOCKET;
1218#ifndef RT_OS_DARWIN
1219 const int icmpstype = SOCK_RAW;
1220#else
1221 /* on OS X it's not privileged */
1222 const int icmpstype = SOCK_DGRAM;
1223#endif
1224
1225 icmpsock4 = socket(AF_INET, icmpstype, IPPROTO_ICMP);
1226 if (icmpsock4 == INVALID_SOCKET)
1227 {
1228 perror("IPPROTO_ICMP");
1229 }
1230
1231 if (icmpsock4 != INVALID_SOCKET)
1232 {
1233#ifdef ICMP_FILTER // Linux specific; NB: privileged!
1234 struct icmp_filter flt = {
1235 ~(uint32_t)(
1236 (1U << ICMP_ECHOREPLY)
1237 | (1U << ICMP_DEST_UNREACH)
1238 | (1U << ICMP_TIME_EXCEEDED)
1239 )
1240 };
1241
1242 int status = setsockopt(icmpsock4, icmpstype, ICMP_FILTER,
1243 &flt, sizeof(flt));
1244 if (status < 0)
1245 {
1246 perror("ICMP_FILTER");
1247 }
1248#endif
1249 }
1250
1251 icmpsock6 = socket(AF_INET6, SOCK_RAW, IPPROTO_ICMPV6);
1252 if (icmpsock6 == INVALID_SOCKET)
1253 {
1254 perror("IPPROTO_ICMPV6");
1255 }
1256
1257 if (icmpsock6 != INVALID_SOCKET)
1258 {
1259#ifdef ICMP6_FILTER // Windows doesn't support RFC 3542 API
1260 /*
1261 * XXX: We do this here for now, not in pxping.c, to avoid
1262 * name clashes between lwIP and system headers.
1263 */
1264 struct icmp6_filter flt;
1265 ICMP6_FILTER_SETBLOCKALL(&flt);
1266
1267 ICMP6_FILTER_SETPASS(ICMP6_ECHO_REPLY, &flt);
1268
1269 ICMP6_FILTER_SETPASS(ICMP6_DST_UNREACH, &flt);
1270 ICMP6_FILTER_SETPASS(ICMP6_PACKET_TOO_BIG, &flt);
1271 ICMP6_FILTER_SETPASS(ICMP6_TIME_EXCEEDED, &flt);
1272 ICMP6_FILTER_SETPASS(ICMP6_PARAM_PROB, &flt);
1273
1274 int status = setsockopt(icmpsock6, IPPROTO_ICMPV6, ICMP6_FILTER,
1275 &flt, sizeof(flt));
1276 if (status < 0)
1277 {
1278 perror("ICMP6_FILTER");
1279 }
1280#endif
1281 }
1282
1283 HRESULT hrc = com::Initialize();
1284#ifdef VBOX_WITH_XPCOM
1285 if (hrc == NS_ERROR_FILE_ACCESS_DENIED)
1286 {
1287 char szHome[RTPATH_MAX] = "";
1288 com::GetVBoxUserHomeDirectory(szHome, sizeof(szHome));
1289 return RTMsgErrorExit(RTEXITCODE_FAILURE,
1290 "Failed to initialize COM because the global settings directory '%s' is not accessible!", szHome);
1291 }
1292#endif
1293 if (FAILED(hrc))
1294 return RTMsgErrorExit(RTEXITCODE_FAILURE, "Failed to initialize COM!");
1295
1296 g_pLwipNat = new VBoxNetLwipNAT(icmpsock4, icmpsock6);
1297
1298 Log2(("NAT: initialization\n"));
1299 int rc = g_pLwipNat->parseArgs(argc - 1, argv + 1);
1300 rc = (rc == 0) ? VINF_SUCCESS : VERR_GENERAL_FAILURE; /* XXX: FIXME */
1301
1302 if (RT_SUCCESS(rc))
1303 {
1304 rc = g_pLwipNat->init();
1305 }
1306
1307 if (RT_SUCCESS(rc))
1308 {
1309 g_pLwipNat->run();
1310 }
1311
1312 delete g_pLwipNat;
1313 return 0;
1314}
1315
1316
1317#ifndef VBOX_WITH_HARDENING
1318
1319int main(int argc, char **argv, char **envp)
1320{
1321 int rc = RTR3InitExe(argc, &argv, RTR3INIT_FLAGS_SUPLIB);
1322 if (RT_FAILURE(rc))
1323 return RTMsgInitFailure(rc);
1324
1325 return TrustedMain(argc, argv, envp);
1326}
1327
1328# if defined(RT_OS_WINDOWS)
1329
1330static LRESULT CALLBACK WindowProc(HWND hwnd,
1331 UINT uMsg,
1332 WPARAM wParam,
1333 LPARAM lParam
1334)
1335{
1336 if(uMsg == WM_DESTROY)
1337 {
1338 PostQuitMessage(0);
1339 return 0;
1340 }
1341 return DefWindowProc (hwnd, uMsg, wParam, lParam);
1342}
1343
1344static LPCWSTR g_WndClassName = L"VBoxNetNatLwipClass";
1345
1346static DWORD WINAPI MsgThreadProc(__in LPVOID lpParameter)
1347{
1348 HWND hwnd = 0;
1349 HINSTANCE hInstance = (HINSTANCE)GetModuleHandle (NULL);
1350 bool bExit = false;
1351
1352 /* Register the Window Class. */
1353 WNDCLASS wc;
1354 wc.style = 0;
1355 wc.lpfnWndProc = WindowProc;
1356 wc.cbClsExtra = 0;
1357 wc.cbWndExtra = sizeof(void *);
1358 wc.hInstance = hInstance;
1359 wc.hIcon = NULL;
1360 wc.hCursor = NULL;
1361 wc.hbrBackground = (HBRUSH)(COLOR_BACKGROUND + 1);
1362 wc.lpszMenuName = NULL;
1363 wc.lpszClassName = g_WndClassName;
1364
1365 ATOM atomWindowClass = RegisterClass(&wc);
1366
1367 if (atomWindowClass != 0)
1368 {
1369 /* Create the window. */
1370 hwnd = CreateWindowEx (WS_EX_TOOLWINDOW | WS_EX_TRANSPARENT | WS_EX_TOPMOST,
1371 g_WndClassName, g_WndClassName,
1372 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.

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