VirtualBox

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

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

Do not configure IPv6 addresses and netif::output_ip6 method on the
proxy netif if IPv6 is disabled for this NAT network.

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