VirtualBox

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

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

Print ifconfig-like information about proxy netif to release log.

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