VirtualBox

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

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

VBoxNetLwipNAT::natServicePfRegister: fix trivial constness XXX.

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